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   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
311   if (!BuiltinID)
312     return;
313 
314   unsigned DiagID = 0;
315   bool IsChkVariant = false;
316   unsigned SizeIndex, ObjectIndex;
317   switch (BuiltinID) {
318   default:
319     return;
320   case Builtin::BI__builtin___memcpy_chk:
321   case Builtin::BI__builtin___memmove_chk:
322   case Builtin::BI__builtin___memset_chk:
323   case Builtin::BI__builtin___strlcat_chk:
324   case Builtin::BI__builtin___strlcpy_chk:
325   case Builtin::BI__builtin___strncat_chk:
326   case Builtin::BI__builtin___strncpy_chk:
327   case Builtin::BI__builtin___stpncpy_chk:
328   case Builtin::BI__builtin___memccpy_chk: {
329     DiagID = diag::warn_builtin_chk_overflow;
330     IsChkVariant = true;
331     SizeIndex = TheCall->getNumArgs() - 2;
332     ObjectIndex = TheCall->getNumArgs() - 1;
333     break;
334   }
335 
336   case Builtin::BI__builtin___snprintf_chk:
337   case Builtin::BI__builtin___vsnprintf_chk: {
338     DiagID = diag::warn_builtin_chk_overflow;
339     IsChkVariant = true;
340     SizeIndex = 1;
341     ObjectIndex = 3;
342     break;
343   }
344 
345   case Builtin::BIstrncat:
346   case Builtin::BI__builtin_strncat:
347   case Builtin::BIstrncpy:
348   case Builtin::BI__builtin_strncpy:
349   case Builtin::BIstpncpy:
350   case Builtin::BI__builtin_stpncpy: {
351     // Whether these functions overflow depends on the runtime strlen of the
352     // string, not just the buffer size, so emitting the "always overflow"
353     // diagnostic isn't quite right. We should still diagnose passing a buffer
354     // size larger than the destination buffer though; this is a runtime abort
355     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
356     DiagID = diag::warn_fortify_source_size_mismatch;
357     SizeIndex = TheCall->getNumArgs() - 1;
358     ObjectIndex = 0;
359     break;
360   }
361 
362   case Builtin::BImemcpy:
363   case Builtin::BI__builtin_memcpy:
364   case Builtin::BImemmove:
365   case Builtin::BI__builtin_memmove:
366   case Builtin::BImemset:
367   case Builtin::BI__builtin_memset: {
368     DiagID = diag::warn_fortify_source_overflow;
369     SizeIndex = TheCall->getNumArgs() - 1;
370     ObjectIndex = 0;
371     break;
372   }
373   case Builtin::BIsnprintf:
374   case Builtin::BI__builtin_snprintf:
375   case Builtin::BIvsnprintf:
376   case Builtin::BI__builtin_vsnprintf: {
377     DiagID = diag::warn_fortify_source_size_mismatch;
378     SizeIndex = 1;
379     ObjectIndex = 0;
380     break;
381   }
382   }
383 
384   llvm::APSInt ObjectSize;
385   // For __builtin___*_chk, the object size is explicitly provided by the caller
386   // (usually using __builtin_object_size). Use that value to check this call.
387   if (IsChkVariant) {
388     Expr::EvalResult Result;
389     Expr *SizeArg = TheCall->getArg(ObjectIndex);
390     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
391       return;
392     ObjectSize = Result.Val.getInt();
393 
394   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
395   } else {
396     // If the parameter has a pass_object_size attribute, then we should use its
397     // (potentially) more strict checking mode. Otherwise, conservatively assume
398     // type 0.
399     int BOSType = 0;
400     if (const auto *POS =
401             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
402       BOSType = POS->getType();
403 
404     Expr *ObjArg = TheCall->getArg(ObjectIndex);
405     uint64_t Result;
406     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
407       return;
408     // Get the object size in the target's size_t width.
409     const TargetInfo &TI = getASTContext().getTargetInfo();
410     unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
411     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
412   }
413 
414   // Evaluate the number of bytes of the object that this call will use.
415   Expr::EvalResult Result;
416   Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
417   if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
418     return;
419   llvm::APSInt UsedSize = Result.Val.getInt();
420 
421   if (UsedSize.ule(ObjectSize))
422     return;
423 
424   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
425   // Skim off the details of whichever builtin was called to produce a better
426   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
427   if (IsChkVariant) {
428     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
429     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
430   } else if (FunctionName.startswith("__builtin_")) {
431     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
432   }
433 
434   Diag(TheCall->getBeginLoc(), DiagID)
435       << FunctionName << ObjectSize.toString(/*Radix=*/10)
436       << UsedSize.toString(/*Radix=*/10);
437 }
438 
439 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
440                                      Scope::ScopeFlags NeededScopeFlags,
441                                      unsigned DiagID) {
442   // Scopes aren't available during instantiation. Fortunately, builtin
443   // functions cannot be template args so they cannot be formed through template
444   // instantiation. Therefore checking once during the parse is sufficient.
445   if (SemaRef.inTemplateInstantiation())
446     return false;
447 
448   Scope *S = SemaRef.getCurScope();
449   while (S && !S->isSEHExceptScope())
450     S = S->getParent();
451   if (!S || !(S->getFlags() & NeededScopeFlags)) {
452     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
453     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
454         << DRE->getDecl()->getIdentifier();
455     return true;
456   }
457 
458   return false;
459 }
460 
461 static inline bool isBlockPointer(Expr *Arg) {
462   return Arg->getType()->isBlockPointerType();
463 }
464 
465 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
466 /// void*, which is a requirement of device side enqueue.
467 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
468   const BlockPointerType *BPT =
469       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
470   ArrayRef<QualType> Params =
471       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
472   unsigned ArgCounter = 0;
473   bool IllegalParams = false;
474   // Iterate through the block parameters until either one is found that is not
475   // a local void*, or the block is valid.
476   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
477        I != E; ++I, ++ArgCounter) {
478     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
479         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
480             LangAS::opencl_local) {
481       // Get the location of the error. If a block literal has been passed
482       // (BlockExpr) then we can point straight to the offending argument,
483       // else we just point to the variable reference.
484       SourceLocation ErrorLoc;
485       if (isa<BlockExpr>(BlockArg)) {
486         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
487         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
488       } else if (isa<DeclRefExpr>(BlockArg)) {
489         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
490       }
491       S.Diag(ErrorLoc,
492              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
493       IllegalParams = true;
494     }
495   }
496 
497   return IllegalParams;
498 }
499 
500 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
501   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
502     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
503         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
504     return true;
505   }
506   return false;
507 }
508 
509 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
510   if (checkArgCount(S, TheCall, 2))
511     return true;
512 
513   if (checkOpenCLSubgroupExt(S, TheCall))
514     return true;
515 
516   // First argument is an ndrange_t type.
517   Expr *NDRangeArg = TheCall->getArg(0);
518   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
519     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
520         << TheCall->getDirectCallee() << "'ndrange_t'";
521     return true;
522   }
523 
524   Expr *BlockArg = TheCall->getArg(1);
525   if (!isBlockPointer(BlockArg)) {
526     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
527         << TheCall->getDirectCallee() << "block";
528     return true;
529   }
530   return checkOpenCLBlockArgs(S, BlockArg);
531 }
532 
533 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
534 /// get_kernel_work_group_size
535 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
536 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
537   if (checkArgCount(S, TheCall, 1))
538     return true;
539 
540   Expr *BlockArg = TheCall->getArg(0);
541   if (!isBlockPointer(BlockArg)) {
542     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
543         << TheCall->getDirectCallee() << "block";
544     return true;
545   }
546   return checkOpenCLBlockArgs(S, BlockArg);
547 }
548 
549 /// Diagnose integer type and any valid implicit conversion to it.
550 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
551                                       const QualType &IntType);
552 
553 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
554                                             unsigned Start, unsigned End) {
555   bool IllegalParams = false;
556   for (unsigned I = Start; I <= End; ++I)
557     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
558                                               S.Context.getSizeType());
559   return IllegalParams;
560 }
561 
562 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
563 /// 'local void*' parameter of passed block.
564 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
565                                            Expr *BlockArg,
566                                            unsigned NumNonVarArgs) {
567   const BlockPointerType *BPT =
568       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
569   unsigned NumBlockParams =
570       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
571   unsigned TotalNumArgs = TheCall->getNumArgs();
572 
573   // For each argument passed to the block, a corresponding uint needs to
574   // be passed to describe the size of the local memory.
575   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
576     S.Diag(TheCall->getBeginLoc(),
577            diag::err_opencl_enqueue_kernel_local_size_args);
578     return true;
579   }
580 
581   // Check that the sizes of the local memory are specified by integers.
582   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
583                                          TotalNumArgs - 1);
584 }
585 
586 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
587 /// overload formats specified in Table 6.13.17.1.
588 /// int enqueue_kernel(queue_t queue,
589 ///                    kernel_enqueue_flags_t flags,
590 ///                    const ndrange_t ndrange,
591 ///                    void (^block)(void))
592 /// int enqueue_kernel(queue_t queue,
593 ///                    kernel_enqueue_flags_t flags,
594 ///                    const ndrange_t ndrange,
595 ///                    uint num_events_in_wait_list,
596 ///                    clk_event_t *event_wait_list,
597 ///                    clk_event_t *event_ret,
598 ///                    void (^block)(void))
599 /// int enqueue_kernel(queue_t queue,
600 ///                    kernel_enqueue_flags_t flags,
601 ///                    const ndrange_t ndrange,
602 ///                    void (^block)(local void*, ...),
603 ///                    uint size0, ...)
604 /// int enqueue_kernel(queue_t queue,
605 ///                    kernel_enqueue_flags_t flags,
606 ///                    const ndrange_t ndrange,
607 ///                    uint num_events_in_wait_list,
608 ///                    clk_event_t *event_wait_list,
609 ///                    clk_event_t *event_ret,
610 ///                    void (^block)(local void*, ...),
611 ///                    uint size0, ...)
612 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
613   unsigned NumArgs = TheCall->getNumArgs();
614 
615   if (NumArgs < 4) {
616     S.Diag(TheCall->getBeginLoc(), diag::err_typecheck_call_too_few_args);
617     return true;
618   }
619 
620   Expr *Arg0 = TheCall->getArg(0);
621   Expr *Arg1 = TheCall->getArg(1);
622   Expr *Arg2 = TheCall->getArg(2);
623   Expr *Arg3 = TheCall->getArg(3);
624 
625   // First argument always needs to be a queue_t type.
626   if (!Arg0->getType()->isQueueT()) {
627     S.Diag(TheCall->getArg(0)->getBeginLoc(),
628            diag::err_opencl_builtin_expected_type)
629         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
630     return true;
631   }
632 
633   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
634   if (!Arg1->getType()->isIntegerType()) {
635     S.Diag(TheCall->getArg(1)->getBeginLoc(),
636            diag::err_opencl_builtin_expected_type)
637         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
638     return true;
639   }
640 
641   // Third argument is always an ndrange_t type.
642   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
643     S.Diag(TheCall->getArg(2)->getBeginLoc(),
644            diag::err_opencl_builtin_expected_type)
645         << TheCall->getDirectCallee() << "'ndrange_t'";
646     return true;
647   }
648 
649   // With four arguments, there is only one form that the function could be
650   // called in: no events and no variable arguments.
651   if (NumArgs == 4) {
652     // check that the last argument is the right block type.
653     if (!isBlockPointer(Arg3)) {
654       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
655           << TheCall->getDirectCallee() << "block";
656       return true;
657     }
658     // we have a block type, check the prototype
659     const BlockPointerType *BPT =
660         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
661     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
662       S.Diag(Arg3->getBeginLoc(),
663              diag::err_opencl_enqueue_kernel_blocks_no_args);
664       return true;
665     }
666     return false;
667   }
668   // we can have block + varargs.
669   if (isBlockPointer(Arg3))
670     return (checkOpenCLBlockArgs(S, Arg3) ||
671             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
672   // last two cases with either exactly 7 args or 7 args and varargs.
673   if (NumArgs >= 7) {
674     // check common block argument.
675     Expr *Arg6 = TheCall->getArg(6);
676     if (!isBlockPointer(Arg6)) {
677       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
678           << TheCall->getDirectCallee() << "block";
679       return true;
680     }
681     if (checkOpenCLBlockArgs(S, Arg6))
682       return true;
683 
684     // Forth argument has to be any integer type.
685     if (!Arg3->getType()->isIntegerType()) {
686       S.Diag(TheCall->getArg(3)->getBeginLoc(),
687              diag::err_opencl_builtin_expected_type)
688           << TheCall->getDirectCallee() << "integer";
689       return true;
690     }
691     // check remaining common arguments.
692     Expr *Arg4 = TheCall->getArg(4);
693     Expr *Arg5 = TheCall->getArg(5);
694 
695     // Fifth argument is always passed as a pointer to clk_event_t.
696     if (!Arg4->isNullPointerConstant(S.Context,
697                                      Expr::NPC_ValueDependentIsNotNull) &&
698         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
699       S.Diag(TheCall->getArg(4)->getBeginLoc(),
700              diag::err_opencl_builtin_expected_type)
701           << TheCall->getDirectCallee()
702           << S.Context.getPointerType(S.Context.OCLClkEventTy);
703       return true;
704     }
705 
706     // Sixth argument is always passed as a pointer to clk_event_t.
707     if (!Arg5->isNullPointerConstant(S.Context,
708                                      Expr::NPC_ValueDependentIsNotNull) &&
709         !(Arg5->getType()->isPointerType() &&
710           Arg5->getType()->getPointeeType()->isClkEventT())) {
711       S.Diag(TheCall->getArg(5)->getBeginLoc(),
712              diag::err_opencl_builtin_expected_type)
713           << TheCall->getDirectCallee()
714           << S.Context.getPointerType(S.Context.OCLClkEventTy);
715       return true;
716     }
717 
718     if (NumArgs == 7)
719       return false;
720 
721     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
722   }
723 
724   // None of the specific case has been detected, give generic error
725   S.Diag(TheCall->getBeginLoc(),
726          diag::err_opencl_enqueue_kernel_incorrect_args);
727   return true;
728 }
729 
730 /// Returns OpenCL access qual.
731 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
732     return D->getAttr<OpenCLAccessAttr>();
733 }
734 
735 /// Returns true if pipe element type is different from the pointer.
736 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
737   const Expr *Arg0 = Call->getArg(0);
738   // First argument type should always be pipe.
739   if (!Arg0->getType()->isPipeType()) {
740     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
741         << Call->getDirectCallee() << Arg0->getSourceRange();
742     return true;
743   }
744   OpenCLAccessAttr *AccessQual =
745       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
746   // Validates the access qualifier is compatible with the call.
747   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
748   // read_only and write_only, and assumed to be read_only if no qualifier is
749   // specified.
750   switch (Call->getDirectCallee()->getBuiltinID()) {
751   case Builtin::BIread_pipe:
752   case Builtin::BIreserve_read_pipe:
753   case Builtin::BIcommit_read_pipe:
754   case Builtin::BIwork_group_reserve_read_pipe:
755   case Builtin::BIsub_group_reserve_read_pipe:
756   case Builtin::BIwork_group_commit_read_pipe:
757   case Builtin::BIsub_group_commit_read_pipe:
758     if (!(!AccessQual || AccessQual->isReadOnly())) {
759       S.Diag(Arg0->getBeginLoc(),
760              diag::err_opencl_builtin_pipe_invalid_access_modifier)
761           << "read_only" << Arg0->getSourceRange();
762       return true;
763     }
764     break;
765   case Builtin::BIwrite_pipe:
766   case Builtin::BIreserve_write_pipe:
767   case Builtin::BIcommit_write_pipe:
768   case Builtin::BIwork_group_reserve_write_pipe:
769   case Builtin::BIsub_group_reserve_write_pipe:
770   case Builtin::BIwork_group_commit_write_pipe:
771   case Builtin::BIsub_group_commit_write_pipe:
772     if (!(AccessQual && AccessQual->isWriteOnly())) {
773       S.Diag(Arg0->getBeginLoc(),
774              diag::err_opencl_builtin_pipe_invalid_access_modifier)
775           << "write_only" << Arg0->getSourceRange();
776       return true;
777     }
778     break;
779   default:
780     break;
781   }
782   return false;
783 }
784 
785 /// Returns true if pipe element type is different from the pointer.
786 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
787   const Expr *Arg0 = Call->getArg(0);
788   const Expr *ArgIdx = Call->getArg(Idx);
789   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
790   const QualType EltTy = PipeTy->getElementType();
791   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
792   // The Idx argument should be a pointer and the type of the pointer and
793   // the type of pipe element should also be the same.
794   if (!ArgTy ||
795       !S.Context.hasSameType(
796           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
797     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
798         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
799         << ArgIdx->getType() << ArgIdx->getSourceRange();
800     return true;
801   }
802   return false;
803 }
804 
805 // Performs semantic analysis for the read/write_pipe call.
806 // \param S Reference to the semantic analyzer.
807 // \param Call A pointer to the builtin call.
808 // \return True if a semantic error has been found, false otherwise.
809 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
810   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
811   // functions have two forms.
812   switch (Call->getNumArgs()) {
813   case 2:
814     if (checkOpenCLPipeArg(S, Call))
815       return true;
816     // The call with 2 arguments should be
817     // read/write_pipe(pipe T, T*).
818     // Check packet type T.
819     if (checkOpenCLPipePacketType(S, Call, 1))
820       return true;
821     break;
822 
823   case 4: {
824     if (checkOpenCLPipeArg(S, Call))
825       return true;
826     // The call with 4 arguments should be
827     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
828     // Check reserve_id_t.
829     if (!Call->getArg(1)->getType()->isReserveIDT()) {
830       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
831           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
832           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
833       return true;
834     }
835 
836     // Check the index.
837     const Expr *Arg2 = Call->getArg(2);
838     if (!Arg2->getType()->isIntegerType() &&
839         !Arg2->getType()->isUnsignedIntegerType()) {
840       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
841           << Call->getDirectCallee() << S.Context.UnsignedIntTy
842           << Arg2->getType() << Arg2->getSourceRange();
843       return true;
844     }
845 
846     // Check packet type T.
847     if (checkOpenCLPipePacketType(S, Call, 3))
848       return true;
849   } break;
850   default:
851     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
852         << Call->getDirectCallee() << Call->getSourceRange();
853     return true;
854   }
855 
856   return false;
857 }
858 
859 // Performs a semantic analysis on the {work_group_/sub_group_
860 //        /_}reserve_{read/write}_pipe
861 // \param S Reference to the semantic analyzer.
862 // \param Call The call to the builtin function to be analyzed.
863 // \return True if a semantic error was found, false otherwise.
864 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
865   if (checkArgCount(S, Call, 2))
866     return true;
867 
868   if (checkOpenCLPipeArg(S, Call))
869     return true;
870 
871   // Check the reserve size.
872   if (!Call->getArg(1)->getType()->isIntegerType() &&
873       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
874     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
875         << Call->getDirectCallee() << S.Context.UnsignedIntTy
876         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
877     return true;
878   }
879 
880   // Since return type of reserve_read/write_pipe built-in function is
881   // reserve_id_t, which is not defined in the builtin def file , we used int
882   // as return type and need to override the return type of these functions.
883   Call->setType(S.Context.OCLReserveIDTy);
884 
885   return false;
886 }
887 
888 // Performs a semantic analysis on {work_group_/sub_group_
889 //        /_}commit_{read/write}_pipe
890 // \param S Reference to the semantic analyzer.
891 // \param Call The call to the builtin function to be analyzed.
892 // \return True if a semantic error was found, false otherwise.
893 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
894   if (checkArgCount(S, Call, 2))
895     return true;
896 
897   if (checkOpenCLPipeArg(S, Call))
898     return true;
899 
900   // Check reserve_id_t.
901   if (!Call->getArg(1)->getType()->isReserveIDT()) {
902     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
903         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
904         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
905     return true;
906   }
907 
908   return false;
909 }
910 
911 // Performs a semantic analysis on the call to built-in Pipe
912 //        Query Functions.
913 // \param S Reference to the semantic analyzer.
914 // \param Call The call to the builtin function to be analyzed.
915 // \return True if a semantic error was found, false otherwise.
916 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
917   if (checkArgCount(S, Call, 1))
918     return true;
919 
920   if (!Call->getArg(0)->getType()->isPipeType()) {
921     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
922         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
923     return true;
924   }
925 
926   return false;
927 }
928 
929 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
930 // Performs semantic analysis for the to_global/local/private call.
931 // \param S Reference to the semantic analyzer.
932 // \param BuiltinID ID of the builtin function.
933 // \param Call A pointer to the builtin call.
934 // \return True if a semantic error has been found, false otherwise.
935 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
936                                     CallExpr *Call) {
937   if (Call->getNumArgs() != 1) {
938     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num)
939         << Call->getDirectCallee() << Call->getSourceRange();
940     return true;
941   }
942 
943   auto RT = Call->getArg(0)->getType();
944   if (!RT->isPointerType() || RT->getPointeeType()
945       .getAddressSpace() == LangAS::opencl_constant) {
946     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
947         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
948     return true;
949   }
950 
951   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
952     S.Diag(Call->getArg(0)->getBeginLoc(),
953            diag::warn_opencl_generic_address_space_arg)
954         << Call->getDirectCallee()->getNameInfo().getAsString()
955         << Call->getArg(0)->getSourceRange();
956   }
957 
958   RT = RT->getPointeeType();
959   auto Qual = RT.getQualifiers();
960   switch (BuiltinID) {
961   case Builtin::BIto_global:
962     Qual.setAddressSpace(LangAS::opencl_global);
963     break;
964   case Builtin::BIto_local:
965     Qual.setAddressSpace(LangAS::opencl_local);
966     break;
967   case Builtin::BIto_private:
968     Qual.setAddressSpace(LangAS::opencl_private);
969     break;
970   default:
971     llvm_unreachable("Invalid builtin function");
972   }
973   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
974       RT.getUnqualifiedType(), Qual)));
975 
976   return false;
977 }
978 
979 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
980   if (checkArgCount(S, TheCall, 1))
981     return ExprError();
982 
983   // Compute __builtin_launder's parameter type from the argument.
984   // The parameter type is:
985   //  * The type of the argument if it's not an array or function type,
986   //  Otherwise,
987   //  * The decayed argument type.
988   QualType ParamTy = [&]() {
989     QualType ArgTy = TheCall->getArg(0)->getType();
990     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
991       return S.Context.getPointerType(Ty->getElementType());
992     if (ArgTy->isFunctionType()) {
993       return S.Context.getPointerType(ArgTy);
994     }
995     return ArgTy;
996   }();
997 
998   TheCall->setType(ParamTy);
999 
1000   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1001     if (!ParamTy->isPointerType())
1002       return 0;
1003     if (ParamTy->isFunctionPointerType())
1004       return 1;
1005     if (ParamTy->isVoidPointerType())
1006       return 2;
1007     return llvm::Optional<unsigned>{};
1008   }();
1009   if (DiagSelect.hasValue()) {
1010     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1011         << DiagSelect.getValue() << TheCall->getSourceRange();
1012     return ExprError();
1013   }
1014 
1015   // We either have an incomplete class type, or we have a class template
1016   // whose instantiation has not been forced. Example:
1017   //
1018   //   template <class T> struct Foo { T value; };
1019   //   Foo<int> *p = nullptr;
1020   //   auto *d = __builtin_launder(p);
1021   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1022                             diag::err_incomplete_type))
1023     return ExprError();
1024 
1025   assert(ParamTy->getPointeeType()->isObjectType() &&
1026          "Unhandled non-object pointer case");
1027 
1028   InitializedEntity Entity =
1029       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1030   ExprResult Arg =
1031       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1032   if (Arg.isInvalid())
1033     return ExprError();
1034   TheCall->setArg(0, Arg.get());
1035 
1036   return TheCall;
1037 }
1038 
1039 // Emit an error and return true if the current architecture is not in the list
1040 // of supported architectures.
1041 static bool
1042 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1043                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1044   llvm::Triple::ArchType CurArch =
1045       S.getASTContext().getTargetInfo().getTriple().getArch();
1046   if (llvm::is_contained(SupportedArchs, CurArch))
1047     return false;
1048   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1049       << TheCall->getSourceRange();
1050   return true;
1051 }
1052 
1053 ExprResult
1054 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1055                                CallExpr *TheCall) {
1056   ExprResult TheCallResult(TheCall);
1057 
1058   // Find out if any arguments are required to be integer constant expressions.
1059   unsigned ICEArguments = 0;
1060   ASTContext::GetBuiltinTypeError Error;
1061   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1062   if (Error != ASTContext::GE_None)
1063     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1064 
1065   // If any arguments are required to be ICE's, check and diagnose.
1066   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1067     // Skip arguments not required to be ICE's.
1068     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1069 
1070     llvm::APSInt Result;
1071     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1072       return true;
1073     ICEArguments &= ~(1 << ArgNo);
1074   }
1075 
1076   switch (BuiltinID) {
1077   case Builtin::BI__builtin___CFStringMakeConstantString:
1078     assert(TheCall->getNumArgs() == 1 &&
1079            "Wrong # arguments to builtin CFStringMakeConstantString");
1080     if (CheckObjCString(TheCall->getArg(0)))
1081       return ExprError();
1082     break;
1083   case Builtin::BI__builtin_ms_va_start:
1084   case Builtin::BI__builtin_stdarg_start:
1085   case Builtin::BI__builtin_va_start:
1086     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1087       return ExprError();
1088     break;
1089   case Builtin::BI__va_start: {
1090     switch (Context.getTargetInfo().getTriple().getArch()) {
1091     case llvm::Triple::aarch64:
1092     case llvm::Triple::arm:
1093     case llvm::Triple::thumb:
1094       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1095         return ExprError();
1096       break;
1097     default:
1098       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1099         return ExprError();
1100       break;
1101     }
1102     break;
1103   }
1104 
1105   // The acquire, release, and no fence variants are ARM and AArch64 only.
1106   case Builtin::BI_interlockedbittestandset_acq:
1107   case Builtin::BI_interlockedbittestandset_rel:
1108   case Builtin::BI_interlockedbittestandset_nf:
1109   case Builtin::BI_interlockedbittestandreset_acq:
1110   case Builtin::BI_interlockedbittestandreset_rel:
1111   case Builtin::BI_interlockedbittestandreset_nf:
1112     if (CheckBuiltinTargetSupport(
1113             *this, BuiltinID, TheCall,
1114             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1115       return ExprError();
1116     break;
1117 
1118   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1119   case Builtin::BI_bittest64:
1120   case Builtin::BI_bittestandcomplement64:
1121   case Builtin::BI_bittestandreset64:
1122   case Builtin::BI_bittestandset64:
1123   case Builtin::BI_interlockedbittestandreset64:
1124   case Builtin::BI_interlockedbittestandset64:
1125     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1126                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1127                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1128       return ExprError();
1129     break;
1130 
1131   case Builtin::BI__builtin_isgreater:
1132   case Builtin::BI__builtin_isgreaterequal:
1133   case Builtin::BI__builtin_isless:
1134   case Builtin::BI__builtin_islessequal:
1135   case Builtin::BI__builtin_islessgreater:
1136   case Builtin::BI__builtin_isunordered:
1137     if (SemaBuiltinUnorderedCompare(TheCall))
1138       return ExprError();
1139     break;
1140   case Builtin::BI__builtin_fpclassify:
1141     if (SemaBuiltinFPClassification(TheCall, 6))
1142       return ExprError();
1143     break;
1144   case Builtin::BI__builtin_isfinite:
1145   case Builtin::BI__builtin_isinf:
1146   case Builtin::BI__builtin_isinf_sign:
1147   case Builtin::BI__builtin_isnan:
1148   case Builtin::BI__builtin_isnormal:
1149   case Builtin::BI__builtin_signbit:
1150   case Builtin::BI__builtin_signbitf:
1151   case Builtin::BI__builtin_signbitl:
1152     if (SemaBuiltinFPClassification(TheCall, 1))
1153       return ExprError();
1154     break;
1155   case Builtin::BI__builtin_shufflevector:
1156     return SemaBuiltinShuffleVector(TheCall);
1157     // TheCall will be freed by the smart pointer here, but that's fine, since
1158     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1159   case Builtin::BI__builtin_prefetch:
1160     if (SemaBuiltinPrefetch(TheCall))
1161       return ExprError();
1162     break;
1163   case Builtin::BI__builtin_alloca_with_align:
1164     if (SemaBuiltinAllocaWithAlign(TheCall))
1165       return ExprError();
1166     break;
1167   case Builtin::BI__assume:
1168   case Builtin::BI__builtin_assume:
1169     if (SemaBuiltinAssume(TheCall))
1170       return ExprError();
1171     break;
1172   case Builtin::BI__builtin_assume_aligned:
1173     if (SemaBuiltinAssumeAligned(TheCall))
1174       return ExprError();
1175     break;
1176   case Builtin::BI__builtin_dynamic_object_size:
1177   case Builtin::BI__builtin_object_size:
1178     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1179       return ExprError();
1180     break;
1181   case Builtin::BI__builtin_longjmp:
1182     if (SemaBuiltinLongjmp(TheCall))
1183       return ExprError();
1184     break;
1185   case Builtin::BI__builtin_setjmp:
1186     if (SemaBuiltinSetjmp(TheCall))
1187       return ExprError();
1188     break;
1189   case Builtin::BI_setjmp:
1190   case Builtin::BI_setjmpex:
1191     if (checkArgCount(*this, TheCall, 1))
1192       return true;
1193     break;
1194   case Builtin::BI__builtin_classify_type:
1195     if (checkArgCount(*this, TheCall, 1)) return true;
1196     TheCall->setType(Context.IntTy);
1197     break;
1198   case Builtin::BI__builtin_constant_p:
1199     if (checkArgCount(*this, TheCall, 1)) return true;
1200     TheCall->setType(Context.IntTy);
1201     break;
1202   case Builtin::BI__builtin_launder:
1203     return SemaBuiltinLaunder(*this, TheCall);
1204   case Builtin::BI__sync_fetch_and_add:
1205   case Builtin::BI__sync_fetch_and_add_1:
1206   case Builtin::BI__sync_fetch_and_add_2:
1207   case Builtin::BI__sync_fetch_and_add_4:
1208   case Builtin::BI__sync_fetch_and_add_8:
1209   case Builtin::BI__sync_fetch_and_add_16:
1210   case Builtin::BI__sync_fetch_and_sub:
1211   case Builtin::BI__sync_fetch_and_sub_1:
1212   case Builtin::BI__sync_fetch_and_sub_2:
1213   case Builtin::BI__sync_fetch_and_sub_4:
1214   case Builtin::BI__sync_fetch_and_sub_8:
1215   case Builtin::BI__sync_fetch_and_sub_16:
1216   case Builtin::BI__sync_fetch_and_or:
1217   case Builtin::BI__sync_fetch_and_or_1:
1218   case Builtin::BI__sync_fetch_and_or_2:
1219   case Builtin::BI__sync_fetch_and_or_4:
1220   case Builtin::BI__sync_fetch_and_or_8:
1221   case Builtin::BI__sync_fetch_and_or_16:
1222   case Builtin::BI__sync_fetch_and_and:
1223   case Builtin::BI__sync_fetch_and_and_1:
1224   case Builtin::BI__sync_fetch_and_and_2:
1225   case Builtin::BI__sync_fetch_and_and_4:
1226   case Builtin::BI__sync_fetch_and_and_8:
1227   case Builtin::BI__sync_fetch_and_and_16:
1228   case Builtin::BI__sync_fetch_and_xor:
1229   case Builtin::BI__sync_fetch_and_xor_1:
1230   case Builtin::BI__sync_fetch_and_xor_2:
1231   case Builtin::BI__sync_fetch_and_xor_4:
1232   case Builtin::BI__sync_fetch_and_xor_8:
1233   case Builtin::BI__sync_fetch_and_xor_16:
1234   case Builtin::BI__sync_fetch_and_nand:
1235   case Builtin::BI__sync_fetch_and_nand_1:
1236   case Builtin::BI__sync_fetch_and_nand_2:
1237   case Builtin::BI__sync_fetch_and_nand_4:
1238   case Builtin::BI__sync_fetch_and_nand_8:
1239   case Builtin::BI__sync_fetch_and_nand_16:
1240   case Builtin::BI__sync_add_and_fetch:
1241   case Builtin::BI__sync_add_and_fetch_1:
1242   case Builtin::BI__sync_add_and_fetch_2:
1243   case Builtin::BI__sync_add_and_fetch_4:
1244   case Builtin::BI__sync_add_and_fetch_8:
1245   case Builtin::BI__sync_add_and_fetch_16:
1246   case Builtin::BI__sync_sub_and_fetch:
1247   case Builtin::BI__sync_sub_and_fetch_1:
1248   case Builtin::BI__sync_sub_and_fetch_2:
1249   case Builtin::BI__sync_sub_and_fetch_4:
1250   case Builtin::BI__sync_sub_and_fetch_8:
1251   case Builtin::BI__sync_sub_and_fetch_16:
1252   case Builtin::BI__sync_and_and_fetch:
1253   case Builtin::BI__sync_and_and_fetch_1:
1254   case Builtin::BI__sync_and_and_fetch_2:
1255   case Builtin::BI__sync_and_and_fetch_4:
1256   case Builtin::BI__sync_and_and_fetch_8:
1257   case Builtin::BI__sync_and_and_fetch_16:
1258   case Builtin::BI__sync_or_and_fetch:
1259   case Builtin::BI__sync_or_and_fetch_1:
1260   case Builtin::BI__sync_or_and_fetch_2:
1261   case Builtin::BI__sync_or_and_fetch_4:
1262   case Builtin::BI__sync_or_and_fetch_8:
1263   case Builtin::BI__sync_or_and_fetch_16:
1264   case Builtin::BI__sync_xor_and_fetch:
1265   case Builtin::BI__sync_xor_and_fetch_1:
1266   case Builtin::BI__sync_xor_and_fetch_2:
1267   case Builtin::BI__sync_xor_and_fetch_4:
1268   case Builtin::BI__sync_xor_and_fetch_8:
1269   case Builtin::BI__sync_xor_and_fetch_16:
1270   case Builtin::BI__sync_nand_and_fetch:
1271   case Builtin::BI__sync_nand_and_fetch_1:
1272   case Builtin::BI__sync_nand_and_fetch_2:
1273   case Builtin::BI__sync_nand_and_fetch_4:
1274   case Builtin::BI__sync_nand_and_fetch_8:
1275   case Builtin::BI__sync_nand_and_fetch_16:
1276   case Builtin::BI__sync_val_compare_and_swap:
1277   case Builtin::BI__sync_val_compare_and_swap_1:
1278   case Builtin::BI__sync_val_compare_and_swap_2:
1279   case Builtin::BI__sync_val_compare_and_swap_4:
1280   case Builtin::BI__sync_val_compare_and_swap_8:
1281   case Builtin::BI__sync_val_compare_and_swap_16:
1282   case Builtin::BI__sync_bool_compare_and_swap:
1283   case Builtin::BI__sync_bool_compare_and_swap_1:
1284   case Builtin::BI__sync_bool_compare_and_swap_2:
1285   case Builtin::BI__sync_bool_compare_and_swap_4:
1286   case Builtin::BI__sync_bool_compare_and_swap_8:
1287   case Builtin::BI__sync_bool_compare_and_swap_16:
1288   case Builtin::BI__sync_lock_test_and_set:
1289   case Builtin::BI__sync_lock_test_and_set_1:
1290   case Builtin::BI__sync_lock_test_and_set_2:
1291   case Builtin::BI__sync_lock_test_and_set_4:
1292   case Builtin::BI__sync_lock_test_and_set_8:
1293   case Builtin::BI__sync_lock_test_and_set_16:
1294   case Builtin::BI__sync_lock_release:
1295   case Builtin::BI__sync_lock_release_1:
1296   case Builtin::BI__sync_lock_release_2:
1297   case Builtin::BI__sync_lock_release_4:
1298   case Builtin::BI__sync_lock_release_8:
1299   case Builtin::BI__sync_lock_release_16:
1300   case Builtin::BI__sync_swap:
1301   case Builtin::BI__sync_swap_1:
1302   case Builtin::BI__sync_swap_2:
1303   case Builtin::BI__sync_swap_4:
1304   case Builtin::BI__sync_swap_8:
1305   case Builtin::BI__sync_swap_16:
1306     return SemaBuiltinAtomicOverloaded(TheCallResult);
1307   case Builtin::BI__sync_synchronize:
1308     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1309         << TheCall->getCallee()->getSourceRange();
1310     break;
1311   case Builtin::BI__builtin_nontemporal_load:
1312   case Builtin::BI__builtin_nontemporal_store:
1313     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1314 #define BUILTIN(ID, TYPE, ATTRS)
1315 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1316   case Builtin::BI##ID: \
1317     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1318 #include "clang/Basic/Builtins.def"
1319   case Builtin::BI__annotation:
1320     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1321       return ExprError();
1322     break;
1323   case Builtin::BI__builtin_annotation:
1324     if (SemaBuiltinAnnotation(*this, TheCall))
1325       return ExprError();
1326     break;
1327   case Builtin::BI__builtin_addressof:
1328     if (SemaBuiltinAddressof(*this, TheCall))
1329       return ExprError();
1330     break;
1331   case Builtin::BI__builtin_add_overflow:
1332   case Builtin::BI__builtin_sub_overflow:
1333   case Builtin::BI__builtin_mul_overflow:
1334     if (SemaBuiltinOverflow(*this, TheCall))
1335       return ExprError();
1336     break;
1337   case Builtin::BI__builtin_operator_new:
1338   case Builtin::BI__builtin_operator_delete: {
1339     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1340     ExprResult Res =
1341         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1342     if (Res.isInvalid())
1343       CorrectDelayedTyposInExpr(TheCallResult.get());
1344     return Res;
1345   }
1346   case Builtin::BI__builtin_dump_struct: {
1347     // We first want to ensure we are called with 2 arguments
1348     if (checkArgCount(*this, TheCall, 2))
1349       return ExprError();
1350     // Ensure that the first argument is of type 'struct XX *'
1351     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1352     const QualType PtrArgType = PtrArg->getType();
1353     if (!PtrArgType->isPointerType() ||
1354         !PtrArgType->getPointeeType()->isRecordType()) {
1355       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1356           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1357           << "structure pointer";
1358       return ExprError();
1359     }
1360 
1361     // Ensure that the second argument is of type 'FunctionType'
1362     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1363     const QualType FnPtrArgType = FnPtrArg->getType();
1364     if (!FnPtrArgType->isPointerType()) {
1365       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1366           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1367           << FnPtrArgType << "'int (*)(const char *, ...)'";
1368       return ExprError();
1369     }
1370 
1371     const auto *FuncType =
1372         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1373 
1374     if (!FuncType) {
1375       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1376           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1377           << FnPtrArgType << "'int (*)(const char *, ...)'";
1378       return ExprError();
1379     }
1380 
1381     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1382       if (!FT->getNumParams()) {
1383         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1384             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1385             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1386         return ExprError();
1387       }
1388       QualType PT = FT->getParamType(0);
1389       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1390           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1391           !PT->getPointeeType().isConstQualified()) {
1392         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1393             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1394             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1395         return ExprError();
1396       }
1397     }
1398 
1399     TheCall->setType(Context.IntTy);
1400     break;
1401   }
1402   case Builtin::BI__builtin_call_with_static_chain:
1403     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1404       return ExprError();
1405     break;
1406   case Builtin::BI__exception_code:
1407   case Builtin::BI_exception_code:
1408     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1409                                  diag::err_seh___except_block))
1410       return ExprError();
1411     break;
1412   case Builtin::BI__exception_info:
1413   case Builtin::BI_exception_info:
1414     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1415                                  diag::err_seh___except_filter))
1416       return ExprError();
1417     break;
1418   case Builtin::BI__GetExceptionInfo:
1419     if (checkArgCount(*this, TheCall, 1))
1420       return ExprError();
1421 
1422     if (CheckCXXThrowOperand(
1423             TheCall->getBeginLoc(),
1424             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1425             TheCall))
1426       return ExprError();
1427 
1428     TheCall->setType(Context.VoidPtrTy);
1429     break;
1430   // OpenCL v2.0, s6.13.16 - Pipe functions
1431   case Builtin::BIread_pipe:
1432   case Builtin::BIwrite_pipe:
1433     // Since those two functions are declared with var args, we need a semantic
1434     // check for the argument.
1435     if (SemaBuiltinRWPipe(*this, TheCall))
1436       return ExprError();
1437     break;
1438   case Builtin::BIreserve_read_pipe:
1439   case Builtin::BIreserve_write_pipe:
1440   case Builtin::BIwork_group_reserve_read_pipe:
1441   case Builtin::BIwork_group_reserve_write_pipe:
1442     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1443       return ExprError();
1444     break;
1445   case Builtin::BIsub_group_reserve_read_pipe:
1446   case Builtin::BIsub_group_reserve_write_pipe:
1447     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1448         SemaBuiltinReserveRWPipe(*this, TheCall))
1449       return ExprError();
1450     break;
1451   case Builtin::BIcommit_read_pipe:
1452   case Builtin::BIcommit_write_pipe:
1453   case Builtin::BIwork_group_commit_read_pipe:
1454   case Builtin::BIwork_group_commit_write_pipe:
1455     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1456       return ExprError();
1457     break;
1458   case Builtin::BIsub_group_commit_read_pipe:
1459   case Builtin::BIsub_group_commit_write_pipe:
1460     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1461         SemaBuiltinCommitRWPipe(*this, TheCall))
1462       return ExprError();
1463     break;
1464   case Builtin::BIget_pipe_num_packets:
1465   case Builtin::BIget_pipe_max_packets:
1466     if (SemaBuiltinPipePackets(*this, TheCall))
1467       return ExprError();
1468     break;
1469   case Builtin::BIto_global:
1470   case Builtin::BIto_local:
1471   case Builtin::BIto_private:
1472     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1473       return ExprError();
1474     break;
1475   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1476   case Builtin::BIenqueue_kernel:
1477     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1478       return ExprError();
1479     break;
1480   case Builtin::BIget_kernel_work_group_size:
1481   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1482     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1483       return ExprError();
1484     break;
1485   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1486   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1487     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1488       return ExprError();
1489     break;
1490   case Builtin::BI__builtin_os_log_format:
1491   case Builtin::BI__builtin_os_log_format_buffer_size:
1492     if (SemaBuiltinOSLogFormat(TheCall))
1493       return ExprError();
1494     break;
1495   }
1496 
1497   // Since the target specific builtins for each arch overlap, only check those
1498   // of the arch we are compiling for.
1499   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1500     switch (Context.getTargetInfo().getTriple().getArch()) {
1501       case llvm::Triple::arm:
1502       case llvm::Triple::armeb:
1503       case llvm::Triple::thumb:
1504       case llvm::Triple::thumbeb:
1505         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1506           return ExprError();
1507         break;
1508       case llvm::Triple::aarch64:
1509       case llvm::Triple::aarch64_be:
1510         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1511           return ExprError();
1512         break;
1513       case llvm::Triple::hexagon:
1514         if (CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall))
1515           return ExprError();
1516         break;
1517       case llvm::Triple::mips:
1518       case llvm::Triple::mipsel:
1519       case llvm::Triple::mips64:
1520       case llvm::Triple::mips64el:
1521         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1522           return ExprError();
1523         break;
1524       case llvm::Triple::systemz:
1525         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1526           return ExprError();
1527         break;
1528       case llvm::Triple::x86:
1529       case llvm::Triple::x86_64:
1530         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1531           return ExprError();
1532         break;
1533       case llvm::Triple::ppc:
1534       case llvm::Triple::ppc64:
1535       case llvm::Triple::ppc64le:
1536         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1537           return ExprError();
1538         break;
1539       default:
1540         break;
1541     }
1542   }
1543 
1544   return TheCallResult;
1545 }
1546 
1547 // Get the valid immediate range for the specified NEON type code.
1548 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1549   NeonTypeFlags Type(t);
1550   int IsQuad = ForceQuad ? true : Type.isQuad();
1551   switch (Type.getEltType()) {
1552   case NeonTypeFlags::Int8:
1553   case NeonTypeFlags::Poly8:
1554     return shift ? 7 : (8 << IsQuad) - 1;
1555   case NeonTypeFlags::Int16:
1556   case NeonTypeFlags::Poly16:
1557     return shift ? 15 : (4 << IsQuad) - 1;
1558   case NeonTypeFlags::Int32:
1559     return shift ? 31 : (2 << IsQuad) - 1;
1560   case NeonTypeFlags::Int64:
1561   case NeonTypeFlags::Poly64:
1562     return shift ? 63 : (1 << IsQuad) - 1;
1563   case NeonTypeFlags::Poly128:
1564     return shift ? 127 : (1 << IsQuad) - 1;
1565   case NeonTypeFlags::Float16:
1566     assert(!shift && "cannot shift float types!");
1567     return (4 << IsQuad) - 1;
1568   case NeonTypeFlags::Float32:
1569     assert(!shift && "cannot shift float types!");
1570     return (2 << IsQuad) - 1;
1571   case NeonTypeFlags::Float64:
1572     assert(!shift && "cannot shift float types!");
1573     return (1 << IsQuad) - 1;
1574   }
1575   llvm_unreachable("Invalid NeonTypeFlag!");
1576 }
1577 
1578 /// getNeonEltType - Return the QualType corresponding to the elements of
1579 /// the vector type specified by the NeonTypeFlags.  This is used to check
1580 /// the pointer arguments for Neon load/store intrinsics.
1581 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1582                                bool IsPolyUnsigned, bool IsInt64Long) {
1583   switch (Flags.getEltType()) {
1584   case NeonTypeFlags::Int8:
1585     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1586   case NeonTypeFlags::Int16:
1587     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1588   case NeonTypeFlags::Int32:
1589     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1590   case NeonTypeFlags::Int64:
1591     if (IsInt64Long)
1592       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1593     else
1594       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1595                                 : Context.LongLongTy;
1596   case NeonTypeFlags::Poly8:
1597     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1598   case NeonTypeFlags::Poly16:
1599     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1600   case NeonTypeFlags::Poly64:
1601     if (IsInt64Long)
1602       return Context.UnsignedLongTy;
1603     else
1604       return Context.UnsignedLongLongTy;
1605   case NeonTypeFlags::Poly128:
1606     break;
1607   case NeonTypeFlags::Float16:
1608     return Context.HalfTy;
1609   case NeonTypeFlags::Float32:
1610     return Context.FloatTy;
1611   case NeonTypeFlags::Float64:
1612     return Context.DoubleTy;
1613   }
1614   llvm_unreachable("Invalid NeonTypeFlag!");
1615 }
1616 
1617 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1618   llvm::APSInt Result;
1619   uint64_t mask = 0;
1620   unsigned TV = 0;
1621   int PtrArgNum = -1;
1622   bool HasConstPtr = false;
1623   switch (BuiltinID) {
1624 #define GET_NEON_OVERLOAD_CHECK
1625 #include "clang/Basic/arm_neon.inc"
1626 #include "clang/Basic/arm_fp16.inc"
1627 #undef GET_NEON_OVERLOAD_CHECK
1628   }
1629 
1630   // For NEON intrinsics which are overloaded on vector element type, validate
1631   // the immediate which specifies which variant to emit.
1632   unsigned ImmArg = TheCall->getNumArgs()-1;
1633   if (mask) {
1634     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1635       return true;
1636 
1637     TV = Result.getLimitedValue(64);
1638     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1639       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
1640              << TheCall->getArg(ImmArg)->getSourceRange();
1641   }
1642 
1643   if (PtrArgNum >= 0) {
1644     // Check that pointer arguments have the specified type.
1645     Expr *Arg = TheCall->getArg(PtrArgNum);
1646     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1647       Arg = ICE->getSubExpr();
1648     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1649     QualType RHSTy = RHS.get()->getType();
1650 
1651     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1652     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1653                           Arch == llvm::Triple::aarch64_be;
1654     bool IsInt64Long =
1655         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1656     QualType EltTy =
1657         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1658     if (HasConstPtr)
1659       EltTy = EltTy.withConst();
1660     QualType LHSTy = Context.getPointerType(EltTy);
1661     AssignConvertType ConvTy;
1662     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1663     if (RHS.isInvalid())
1664       return true;
1665     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
1666                                  RHS.get(), AA_Assigning))
1667       return true;
1668   }
1669 
1670   // For NEON intrinsics which take an immediate value as part of the
1671   // instruction, range check them here.
1672   unsigned i = 0, l = 0, u = 0;
1673   switch (BuiltinID) {
1674   default:
1675     return false;
1676   #define GET_NEON_IMMEDIATE_CHECK
1677   #include "clang/Basic/arm_neon.inc"
1678   #include "clang/Basic/arm_fp16.inc"
1679   #undef GET_NEON_IMMEDIATE_CHECK
1680   }
1681 
1682   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1683 }
1684 
1685 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1686                                         unsigned MaxWidth) {
1687   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1688           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1689           BuiltinID == ARM::BI__builtin_arm_strex ||
1690           BuiltinID == ARM::BI__builtin_arm_stlex ||
1691           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1692           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1693           BuiltinID == AArch64::BI__builtin_arm_strex ||
1694           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1695          "unexpected ARM builtin");
1696   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1697                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1698                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1699                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1700 
1701   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1702 
1703   // Ensure that we have the proper number of arguments.
1704   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1705     return true;
1706 
1707   // Inspect the pointer argument of the atomic builtin.  This should always be
1708   // a pointer type, whose element is an integral scalar or pointer type.
1709   // Because it is a pointer type, we don't have to worry about any implicit
1710   // casts here.
1711   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1712   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1713   if (PointerArgRes.isInvalid())
1714     return true;
1715   PointerArg = PointerArgRes.get();
1716 
1717   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1718   if (!pointerType) {
1719     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
1720         << PointerArg->getType() << PointerArg->getSourceRange();
1721     return true;
1722   }
1723 
1724   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1725   // task is to insert the appropriate casts into the AST. First work out just
1726   // what the appropriate type is.
1727   QualType ValType = pointerType->getPointeeType();
1728   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1729   if (IsLdrex)
1730     AddrType.addConst();
1731 
1732   // Issue a warning if the cast is dodgy.
1733   CastKind CastNeeded = CK_NoOp;
1734   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1735     CastNeeded = CK_BitCast;
1736     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
1737         << PointerArg->getType() << Context.getPointerType(AddrType)
1738         << AA_Passing << PointerArg->getSourceRange();
1739   }
1740 
1741   // Finally, do the cast and replace the argument with the corrected version.
1742   AddrType = Context.getPointerType(AddrType);
1743   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1744   if (PointerArgRes.isInvalid())
1745     return true;
1746   PointerArg = PointerArgRes.get();
1747 
1748   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1749 
1750   // In general, we allow ints, floats and pointers to be loaded and stored.
1751   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1752       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1753     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1754         << PointerArg->getType() << PointerArg->getSourceRange();
1755     return true;
1756   }
1757 
1758   // But ARM doesn't have instructions to deal with 128-bit versions.
1759   if (Context.getTypeSize(ValType) > MaxWidth) {
1760     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1761     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
1762         << PointerArg->getType() << PointerArg->getSourceRange();
1763     return true;
1764   }
1765 
1766   switch (ValType.getObjCLifetime()) {
1767   case Qualifiers::OCL_None:
1768   case Qualifiers::OCL_ExplicitNone:
1769     // okay
1770     break;
1771 
1772   case Qualifiers::OCL_Weak:
1773   case Qualifiers::OCL_Strong:
1774   case Qualifiers::OCL_Autoreleasing:
1775     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
1776         << ValType << PointerArg->getSourceRange();
1777     return true;
1778   }
1779 
1780   if (IsLdrex) {
1781     TheCall->setType(ValType);
1782     return false;
1783   }
1784 
1785   // Initialize the argument to be stored.
1786   ExprResult ValArg = TheCall->getArg(0);
1787   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1788       Context, ValType, /*consume*/ false);
1789   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1790   if (ValArg.isInvalid())
1791     return true;
1792   TheCall->setArg(0, ValArg.get());
1793 
1794   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1795   // but the custom checker bypasses all default analysis.
1796   TheCall->setType(Context.IntTy);
1797   return false;
1798 }
1799 
1800 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1801   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1802       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1803       BuiltinID == ARM::BI__builtin_arm_strex ||
1804       BuiltinID == ARM::BI__builtin_arm_stlex) {
1805     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1806   }
1807 
1808   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1809     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1810       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1811   }
1812 
1813   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1814       BuiltinID == ARM::BI__builtin_arm_wsr64)
1815     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1816 
1817   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1818       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1819       BuiltinID == ARM::BI__builtin_arm_wsr ||
1820       BuiltinID == ARM::BI__builtin_arm_wsrp)
1821     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1822 
1823   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1824     return true;
1825 
1826   // For intrinsics which take an immediate value as part of the instruction,
1827   // range check them here.
1828   // FIXME: VFP Intrinsics should error if VFP not present.
1829   switch (BuiltinID) {
1830   default: return false;
1831   case ARM::BI__builtin_arm_ssat:
1832     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1833   case ARM::BI__builtin_arm_usat:
1834     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1835   case ARM::BI__builtin_arm_ssat16:
1836     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1837   case ARM::BI__builtin_arm_usat16:
1838     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1839   case ARM::BI__builtin_arm_vcvtr_f:
1840   case ARM::BI__builtin_arm_vcvtr_d:
1841     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1842   case ARM::BI__builtin_arm_dmb:
1843   case ARM::BI__builtin_arm_dsb:
1844   case ARM::BI__builtin_arm_isb:
1845   case ARM::BI__builtin_arm_dbg:
1846     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1847   }
1848 }
1849 
1850 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1851                                          CallExpr *TheCall) {
1852   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1853       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1854       BuiltinID == AArch64::BI__builtin_arm_strex ||
1855       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1856     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1857   }
1858 
1859   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1860     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1861       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1862       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1863       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1864   }
1865 
1866   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1867       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1868     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1869 
1870   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1871       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1872       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1873       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1874     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1875 
1876   // Only check the valid encoding range. Any constant in this range would be
1877   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
1878   // an exception for incorrect registers. This matches MSVC behavior.
1879   if (BuiltinID == AArch64::BI_ReadStatusReg ||
1880       BuiltinID == AArch64::BI_WriteStatusReg)
1881     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
1882 
1883   if (BuiltinID == AArch64::BI__getReg)
1884     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
1885 
1886   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1887     return true;
1888 
1889   // For intrinsics which take an immediate value as part of the instruction,
1890   // range check them here.
1891   unsigned i = 0, l = 0, u = 0;
1892   switch (BuiltinID) {
1893   default: return false;
1894   case AArch64::BI__builtin_arm_dmb:
1895   case AArch64::BI__builtin_arm_dsb:
1896   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1897   }
1898 
1899   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1900 }
1901 
1902 bool Sema::CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall) {
1903   struct BuiltinAndString {
1904     unsigned BuiltinID;
1905     const char *Str;
1906   };
1907 
1908   static BuiltinAndString ValidCPU[] = {
1909     { Hexagon::BI__builtin_HEXAGON_A6_vcmpbeq_notany, "v65,v66" },
1910     { Hexagon::BI__builtin_HEXAGON_A6_vminub_RdP, "v62,v65,v66" },
1911     { Hexagon::BI__builtin_HEXAGON_F2_dfadd, "v66" },
1912     { Hexagon::BI__builtin_HEXAGON_F2_dfsub, "v66" },
1913     { Hexagon::BI__builtin_HEXAGON_M2_mnaci, "v66" },
1914     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffb, "v62,v65,v66" },
1915     { Hexagon::BI__builtin_HEXAGON_M6_vabsdiffub, "v62,v65,v66" },
1916     { Hexagon::BI__builtin_HEXAGON_S2_mask, "v66" },
1917     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, "v60,v62,v65,v66" },
1918     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, "v60,v62,v65,v66" },
1919     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, "v60,v62,v65,v66" },
1920     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, "v60,v62,v65,v66" },
1921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, "v60,v62,v65,v66" },
1922     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, "v60,v62,v65,v66" },
1923     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, "v60,v62,v65,v66" },
1924     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, "v60,v62,v65,v66" },
1925     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, "v60,v62,v65,v66" },
1926     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, "v60,v62,v65,v66" },
1927     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, "v60,v62,v65,v66" },
1928     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, "v60,v62,v65,v66" },
1929     { Hexagon::BI__builtin_HEXAGON_S6_vsplatrbp, "v62,v65,v66" },
1930     { Hexagon::BI__builtin_HEXAGON_S6_vtrunehb_ppp, "v62,v65,v66" },
1931     { Hexagon::BI__builtin_HEXAGON_S6_vtrunohb_ppp, "v62,v65,v66" },
1932   };
1933 
1934   static BuiltinAndString ValidHVX[] = {
1935     { Hexagon::BI__builtin_HEXAGON_V6_hi, "v60,v62,v65,v66" },
1936     { Hexagon::BI__builtin_HEXAGON_V6_hi_128B, "v60,v62,v65,v66" },
1937     { Hexagon::BI__builtin_HEXAGON_V6_lo, "v60,v62,v65,v66" },
1938     { Hexagon::BI__builtin_HEXAGON_V6_lo_128B, "v60,v62,v65,v66" },
1939     { Hexagon::BI__builtin_HEXAGON_V6_extractw, "v60,v62,v65,v66" },
1940     { Hexagon::BI__builtin_HEXAGON_V6_extractw_128B, "v60,v62,v65,v66" },
1941     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb, "v62,v65,v66" },
1942     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatb_128B, "v62,v65,v66" },
1943     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath, "v62,v65,v66" },
1944     { Hexagon::BI__builtin_HEXAGON_V6_lvsplath_128B, "v62,v65,v66" },
1945     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw, "v60,v62,v65,v66" },
1946     { Hexagon::BI__builtin_HEXAGON_V6_lvsplatw_128B, "v60,v62,v65,v66" },
1947     { Hexagon::BI__builtin_HEXAGON_V6_pred_and, "v60,v62,v65,v66" },
1948     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_128B, "v60,v62,v65,v66" },
1949     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n, "v60,v62,v65,v66" },
1950     { Hexagon::BI__builtin_HEXAGON_V6_pred_and_n_128B, "v60,v62,v65,v66" },
1951     { Hexagon::BI__builtin_HEXAGON_V6_pred_not, "v60,v62,v65,v66" },
1952     { Hexagon::BI__builtin_HEXAGON_V6_pred_not_128B, "v60,v62,v65,v66" },
1953     { Hexagon::BI__builtin_HEXAGON_V6_pred_or, "v60,v62,v65,v66" },
1954     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_128B, "v60,v62,v65,v66" },
1955     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n, "v60,v62,v65,v66" },
1956     { Hexagon::BI__builtin_HEXAGON_V6_pred_or_n_128B, "v60,v62,v65,v66" },
1957     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2, "v60,v62,v65,v66" },
1958     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2_128B, "v60,v62,v65,v66" },
1959     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2, "v62,v65,v66" },
1960     { Hexagon::BI__builtin_HEXAGON_V6_pred_scalar2v2_128B, "v62,v65,v66" },
1961     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor, "v60,v62,v65,v66" },
1962     { Hexagon::BI__builtin_HEXAGON_V6_pred_xor_128B, "v60,v62,v65,v66" },
1963     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh, "v62,v65,v66" },
1964     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqh_128B, "v62,v65,v66" },
1965     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw, "v62,v65,v66" },
1966     { Hexagon::BI__builtin_HEXAGON_V6_shuffeqw_128B, "v62,v65,v66" },
1967     { Hexagon::BI__builtin_HEXAGON_V6_vabsb, "v65,v66" },
1968     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_128B, "v65,v66" },
1969     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat, "v65,v66" },
1970     { Hexagon::BI__builtin_HEXAGON_V6_vabsb_sat_128B, "v65,v66" },
1971     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh, "v60,v62,v65,v66" },
1972     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffh_128B, "v60,v62,v65,v66" },
1973     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub, "v60,v62,v65,v66" },
1974     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffub_128B, "v60,v62,v65,v66" },
1975     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh, "v60,v62,v65,v66" },
1976     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffuh_128B, "v60,v62,v65,v66" },
1977     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw, "v60,v62,v65,v66" },
1978     { Hexagon::BI__builtin_HEXAGON_V6_vabsdiffw_128B, "v60,v62,v65,v66" },
1979     { Hexagon::BI__builtin_HEXAGON_V6_vabsh, "v60,v62,v65,v66" },
1980     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_128B, "v60,v62,v65,v66" },
1981     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat, "v60,v62,v65,v66" },
1982     { Hexagon::BI__builtin_HEXAGON_V6_vabsh_sat_128B, "v60,v62,v65,v66" },
1983     { Hexagon::BI__builtin_HEXAGON_V6_vabsw, "v60,v62,v65,v66" },
1984     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_128B, "v60,v62,v65,v66" },
1985     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat, "v60,v62,v65,v66" },
1986     { Hexagon::BI__builtin_HEXAGON_V6_vabsw_sat_128B, "v60,v62,v65,v66" },
1987     { Hexagon::BI__builtin_HEXAGON_V6_vaddb, "v60,v62,v65,v66" },
1988     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_128B, "v60,v62,v65,v66" },
1989     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv, "v60,v62,v65,v66" },
1990     { Hexagon::BI__builtin_HEXAGON_V6_vaddb_dv_128B, "v60,v62,v65,v66" },
1991     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat, "v62,v65,v66" },
1992     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_128B, "v62,v65,v66" },
1993     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv, "v62,v65,v66" },
1994     { Hexagon::BI__builtin_HEXAGON_V6_vaddbsat_dv_128B, "v62,v65,v66" },
1995     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry, "v62,v65,v66" },
1996     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarry_128B, "v62,v65,v66" },
1997     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat, "v66" },
1998     { Hexagon::BI__builtin_HEXAGON_V6_vaddcarrysat_128B, "v66" },
1999     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh, "v62,v65,v66" },
2000     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbh_128B, "v62,v65,v66" },
2001     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw, "v62,v65,v66" },
2002     { Hexagon::BI__builtin_HEXAGON_V6_vaddclbw_128B, "v62,v65,v66" },
2003     { Hexagon::BI__builtin_HEXAGON_V6_vaddh, "v60,v62,v65,v66" },
2004     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_128B, "v60,v62,v65,v66" },
2005     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv, "v60,v62,v65,v66" },
2006     { Hexagon::BI__builtin_HEXAGON_V6_vaddh_dv_128B, "v60,v62,v65,v66" },
2007     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat, "v60,v62,v65,v66" },
2008     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_128B, "v60,v62,v65,v66" },
2009     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv, "v60,v62,v65,v66" },
2010     { Hexagon::BI__builtin_HEXAGON_V6_vaddhsat_dv_128B, "v60,v62,v65,v66" },
2011     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw, "v60,v62,v65,v66" },
2012     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_128B, "v60,v62,v65,v66" },
2013     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc, "v62,v65,v66" },
2014     { Hexagon::BI__builtin_HEXAGON_V6_vaddhw_acc_128B, "v62,v65,v66" },
2015     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh, "v60,v62,v65,v66" },
2016     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_128B, "v60,v62,v65,v66" },
2017     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc, "v62,v65,v66" },
2018     { Hexagon::BI__builtin_HEXAGON_V6_vaddubh_acc_128B, "v62,v65,v66" },
2019     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat, "v60,v62,v65,v66" },
2020     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_128B, "v60,v62,v65,v66" },
2021     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv, "v60,v62,v65,v66" },
2022     { Hexagon::BI__builtin_HEXAGON_V6_vaddubsat_dv_128B, "v60,v62,v65,v66" },
2023     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat, "v62,v65,v66" },
2024     { Hexagon::BI__builtin_HEXAGON_V6_vaddububb_sat_128B, "v62,v65,v66" },
2025     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat, "v60,v62,v65,v66" },
2026     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_128B, "v60,v62,v65,v66" },
2027     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv, "v60,v62,v65,v66" },
2028     { Hexagon::BI__builtin_HEXAGON_V6_vadduhsat_dv_128B, "v60,v62,v65,v66" },
2029     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw, "v60,v62,v65,v66" },
2030     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_128B, "v60,v62,v65,v66" },
2031     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc, "v62,v65,v66" },
2032     { Hexagon::BI__builtin_HEXAGON_V6_vadduhw_acc_128B, "v62,v65,v66" },
2033     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat, "v62,v65,v66" },
2034     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_128B, "v62,v65,v66" },
2035     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv, "v62,v65,v66" },
2036     { Hexagon::BI__builtin_HEXAGON_V6_vadduwsat_dv_128B, "v62,v65,v66" },
2037     { Hexagon::BI__builtin_HEXAGON_V6_vaddw, "v60,v62,v65,v66" },
2038     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_128B, "v60,v62,v65,v66" },
2039     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv, "v60,v62,v65,v66" },
2040     { Hexagon::BI__builtin_HEXAGON_V6_vaddw_dv_128B, "v60,v62,v65,v66" },
2041     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat, "v60,v62,v65,v66" },
2042     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_128B, "v60,v62,v65,v66" },
2043     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv, "v60,v62,v65,v66" },
2044     { Hexagon::BI__builtin_HEXAGON_V6_vaddwsat_dv_128B, "v60,v62,v65,v66" },
2045     { Hexagon::BI__builtin_HEXAGON_V6_valignb, "v60,v62,v65,v66" },
2046     { Hexagon::BI__builtin_HEXAGON_V6_valignb_128B, "v60,v62,v65,v66" },
2047     { Hexagon::BI__builtin_HEXAGON_V6_valignbi, "v60,v62,v65,v66" },
2048     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, "v60,v62,v65,v66" },
2049     { Hexagon::BI__builtin_HEXAGON_V6_vand, "v60,v62,v65,v66" },
2050     { Hexagon::BI__builtin_HEXAGON_V6_vand_128B, "v60,v62,v65,v66" },
2051     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt, "v62,v65,v66" },
2052     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_128B, "v62,v65,v66" },
2053     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc, "v62,v65,v66" },
2054     { Hexagon::BI__builtin_HEXAGON_V6_vandnqrt_acc_128B, "v62,v65,v66" },
2055     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt, "v60,v62,v65,v66" },
2056     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_128B, "v60,v62,v65,v66" },
2057     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc, "v60,v62,v65,v66" },
2058     { Hexagon::BI__builtin_HEXAGON_V6_vandqrt_acc_128B, "v60,v62,v65,v66" },
2059     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv, "v62,v65,v66" },
2060     { Hexagon::BI__builtin_HEXAGON_V6_vandvnqv_128B, "v62,v65,v66" },
2061     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv, "v62,v65,v66" },
2062     { Hexagon::BI__builtin_HEXAGON_V6_vandvqv_128B, "v62,v65,v66" },
2063     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt, "v60,v62,v65,v66" },
2064     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_128B, "v60,v62,v65,v66" },
2065     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc, "v60,v62,v65,v66" },
2066     { Hexagon::BI__builtin_HEXAGON_V6_vandvrt_acc_128B, "v60,v62,v65,v66" },
2067     { Hexagon::BI__builtin_HEXAGON_V6_vaslh, "v60,v62,v65,v66" },
2068     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_128B, "v60,v62,v65,v66" },
2069     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc, "v65,v66" },
2070     { Hexagon::BI__builtin_HEXAGON_V6_vaslh_acc_128B, "v65,v66" },
2071     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv, "v60,v62,v65,v66" },
2072     { Hexagon::BI__builtin_HEXAGON_V6_vaslhv_128B, "v60,v62,v65,v66" },
2073     { Hexagon::BI__builtin_HEXAGON_V6_vaslw, "v60,v62,v65,v66" },
2074     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_128B, "v60,v62,v65,v66" },
2075     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc, "v60,v62,v65,v66" },
2076     { Hexagon::BI__builtin_HEXAGON_V6_vaslw_acc_128B, "v60,v62,v65,v66" },
2077     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv, "v60,v62,v65,v66" },
2078     { Hexagon::BI__builtin_HEXAGON_V6_vaslwv_128B, "v60,v62,v65,v66" },
2079     { Hexagon::BI__builtin_HEXAGON_V6_vasrh, "v60,v62,v65,v66" },
2080     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_128B, "v60,v62,v65,v66" },
2081     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc, "v65,v66" },
2082     { Hexagon::BI__builtin_HEXAGON_V6_vasrh_acc_128B, "v65,v66" },
2083     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat, "v60,v62,v65,v66" },
2084     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbrndsat_128B, "v60,v62,v65,v66" },
2085     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat, "v62,v65,v66" },
2086     { Hexagon::BI__builtin_HEXAGON_V6_vasrhbsat_128B, "v62,v65,v66" },
2087     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat, "v60,v62,v65,v66" },
2088     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubrndsat_128B, "v60,v62,v65,v66" },
2089     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat, "v60,v62,v65,v66" },
2090     { Hexagon::BI__builtin_HEXAGON_V6_vasrhubsat_128B, "v60,v62,v65,v66" },
2091     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv, "v60,v62,v65,v66" },
2092     { Hexagon::BI__builtin_HEXAGON_V6_vasrhv_128B, "v60,v62,v65,v66" },
2093     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into, "v66" },
2094     { Hexagon::BI__builtin_HEXAGON_V6_vasr_into_128B, "v66" },
2095     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat, "v65,v66" },
2096     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubrndsat_128B, "v65,v66" },
2097     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat, "v65,v66" },
2098     { Hexagon::BI__builtin_HEXAGON_V6_vasruhubsat_128B, "v65,v66" },
2099     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat, "v62,v65,v66" },
2100     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhrndsat_128B, "v62,v65,v66" },
2101     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat, "v65,v66" },
2102     { Hexagon::BI__builtin_HEXAGON_V6_vasruwuhsat_128B, "v65,v66" },
2103     { Hexagon::BI__builtin_HEXAGON_V6_vasrw, "v60,v62,v65,v66" },
2104     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_128B, "v60,v62,v65,v66" },
2105     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc, "v60,v62,v65,v66" },
2106     { Hexagon::BI__builtin_HEXAGON_V6_vasrw_acc_128B, "v60,v62,v65,v66" },
2107     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh, "v60,v62,v65,v66" },
2108     { Hexagon::BI__builtin_HEXAGON_V6_vasrwh_128B, "v60,v62,v65,v66" },
2109     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat, "v60,v62,v65,v66" },
2110     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhrndsat_128B, "v60,v62,v65,v66" },
2111     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat, "v60,v62,v65,v66" },
2112     { Hexagon::BI__builtin_HEXAGON_V6_vasrwhsat_128B, "v60,v62,v65,v66" },
2113     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat, "v62,v65,v66" },
2114     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhrndsat_128B, "v62,v65,v66" },
2115     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat, "v60,v62,v65,v66" },
2116     { Hexagon::BI__builtin_HEXAGON_V6_vasrwuhsat_128B, "v60,v62,v65,v66" },
2117     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv, "v60,v62,v65,v66" },
2118     { Hexagon::BI__builtin_HEXAGON_V6_vasrwv_128B, "v60,v62,v65,v66" },
2119     { Hexagon::BI__builtin_HEXAGON_V6_vassign, "v60,v62,v65,v66" },
2120     { Hexagon::BI__builtin_HEXAGON_V6_vassign_128B, "v60,v62,v65,v66" },
2121     { Hexagon::BI__builtin_HEXAGON_V6_vassignp, "v60,v62,v65,v66" },
2122     { Hexagon::BI__builtin_HEXAGON_V6_vassignp_128B, "v60,v62,v65,v66" },
2123     { Hexagon::BI__builtin_HEXAGON_V6_vavgb, "v65,v66" },
2124     { Hexagon::BI__builtin_HEXAGON_V6_vavgb_128B, "v65,v66" },
2125     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd, "v65,v66" },
2126     { Hexagon::BI__builtin_HEXAGON_V6_vavgbrnd_128B, "v65,v66" },
2127     { Hexagon::BI__builtin_HEXAGON_V6_vavgh, "v60,v62,v65,v66" },
2128     { Hexagon::BI__builtin_HEXAGON_V6_vavgh_128B, "v60,v62,v65,v66" },
2129     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd, "v60,v62,v65,v66" },
2130     { Hexagon::BI__builtin_HEXAGON_V6_vavghrnd_128B, "v60,v62,v65,v66" },
2131     { Hexagon::BI__builtin_HEXAGON_V6_vavgub, "v60,v62,v65,v66" },
2132     { Hexagon::BI__builtin_HEXAGON_V6_vavgub_128B, "v60,v62,v65,v66" },
2133     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd, "v60,v62,v65,v66" },
2134     { Hexagon::BI__builtin_HEXAGON_V6_vavgubrnd_128B, "v60,v62,v65,v66" },
2135     { Hexagon::BI__builtin_HEXAGON_V6_vavguh, "v60,v62,v65,v66" },
2136     { Hexagon::BI__builtin_HEXAGON_V6_vavguh_128B, "v60,v62,v65,v66" },
2137     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd, "v60,v62,v65,v66" },
2138     { Hexagon::BI__builtin_HEXAGON_V6_vavguhrnd_128B, "v60,v62,v65,v66" },
2139     { Hexagon::BI__builtin_HEXAGON_V6_vavguw, "v65,v66" },
2140     { Hexagon::BI__builtin_HEXAGON_V6_vavguw_128B, "v65,v66" },
2141     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd, "v65,v66" },
2142     { Hexagon::BI__builtin_HEXAGON_V6_vavguwrnd_128B, "v65,v66" },
2143     { Hexagon::BI__builtin_HEXAGON_V6_vavgw, "v60,v62,v65,v66" },
2144     { Hexagon::BI__builtin_HEXAGON_V6_vavgw_128B, "v60,v62,v65,v66" },
2145     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd, "v60,v62,v65,v66" },
2146     { Hexagon::BI__builtin_HEXAGON_V6_vavgwrnd_128B, "v60,v62,v65,v66" },
2147     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h, "v60,v62,v65,v66" },
2148     { Hexagon::BI__builtin_HEXAGON_V6_vcl0h_128B, "v60,v62,v65,v66" },
2149     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w, "v60,v62,v65,v66" },
2150     { Hexagon::BI__builtin_HEXAGON_V6_vcl0w_128B, "v60,v62,v65,v66" },
2151     { Hexagon::BI__builtin_HEXAGON_V6_vcombine, "v60,v62,v65,v66" },
2152     { Hexagon::BI__builtin_HEXAGON_V6_vcombine_128B, "v60,v62,v65,v66" },
2153     { Hexagon::BI__builtin_HEXAGON_V6_vd0, "v60,v62,v65,v66" },
2154     { Hexagon::BI__builtin_HEXAGON_V6_vd0_128B, "v60,v62,v65,v66" },
2155     { Hexagon::BI__builtin_HEXAGON_V6_vdd0, "v65,v66" },
2156     { Hexagon::BI__builtin_HEXAGON_V6_vdd0_128B, "v65,v66" },
2157     { Hexagon::BI__builtin_HEXAGON_V6_vdealb, "v60,v62,v65,v66" },
2158     { Hexagon::BI__builtin_HEXAGON_V6_vdealb_128B, "v60,v62,v65,v66" },
2159     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w, "v60,v62,v65,v66" },
2160     { Hexagon::BI__builtin_HEXAGON_V6_vdealb4w_128B, "v60,v62,v65,v66" },
2161     { Hexagon::BI__builtin_HEXAGON_V6_vdealh, "v60,v62,v65,v66" },
2162     { Hexagon::BI__builtin_HEXAGON_V6_vdealh_128B, "v60,v62,v65,v66" },
2163     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd, "v60,v62,v65,v66" },
2164     { Hexagon::BI__builtin_HEXAGON_V6_vdealvdd_128B, "v60,v62,v65,v66" },
2165     { Hexagon::BI__builtin_HEXAGON_V6_vdelta, "v60,v62,v65,v66" },
2166     { Hexagon::BI__builtin_HEXAGON_V6_vdelta_128B, "v60,v62,v65,v66" },
2167     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus, "v60,v62,v65,v66" },
2168     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_128B, "v60,v62,v65,v66" },
2169     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc, "v60,v62,v65,v66" },
2170     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_acc_128B, "v60,v62,v65,v66" },
2171     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv, "v60,v62,v65,v66" },
2172     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_128B, "v60,v62,v65,v66" },
2173     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc, "v60,v62,v65,v66" },
2174     { Hexagon::BI__builtin_HEXAGON_V6_vdmpybus_dv_acc_128B, "v60,v62,v65,v66" },
2175     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb, "v60,v62,v65,v66" },
2176     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_128B, "v60,v62,v65,v66" },
2177     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc, "v60,v62,v65,v66" },
2178     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_acc_128B, "v60,v62,v65,v66" },
2179     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv, "v60,v62,v65,v66" },
2180     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_128B, "v60,v62,v65,v66" },
2181     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc, "v60,v62,v65,v66" },
2182     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhb_dv_acc_128B, "v60,v62,v65,v66" },
2183     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat, "v60,v62,v65,v66" },
2184     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_128B, "v60,v62,v65,v66" },
2185     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc, "v60,v62,v65,v66" },
2186     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhisat_acc_128B, "v60,v62,v65,v66" },
2187     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat, "v60,v62,v65,v66" },
2188     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_128B, "v60,v62,v65,v66" },
2189     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc, "v60,v62,v65,v66" },
2190     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsat_acc_128B, "v60,v62,v65,v66" },
2191     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat, "v60,v62,v65,v66" },
2192     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_128B, "v60,v62,v65,v66" },
2193     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc, "v60,v62,v65,v66" },
2194     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsuisat_acc_128B, "v60,v62,v65,v66" },
2195     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat, "v60,v62,v65,v66" },
2196     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_128B, "v60,v62,v65,v66" },
2197     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc, "v60,v62,v65,v66" },
2198     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhsusat_acc_128B, "v60,v62,v65,v66" },
2199     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat, "v60,v62,v65,v66" },
2200     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_128B, "v60,v62,v65,v66" },
2201     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc, "v60,v62,v65,v66" },
2202     { Hexagon::BI__builtin_HEXAGON_V6_vdmpyhvsat_acc_128B, "v60,v62,v65,v66" },
2203     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh, "v60,v62,v65,v66" },
2204     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_128B, "v60,v62,v65,v66" },
2205     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc, "v60,v62,v65,v66" },
2206     { Hexagon::BI__builtin_HEXAGON_V6_vdsaduh_acc_128B, "v60,v62,v65,v66" },
2207     { Hexagon::BI__builtin_HEXAGON_V6_veqb, "v60,v62,v65,v66" },
2208     { Hexagon::BI__builtin_HEXAGON_V6_veqb_128B, "v60,v62,v65,v66" },
2209     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and, "v60,v62,v65,v66" },
2210     { Hexagon::BI__builtin_HEXAGON_V6_veqb_and_128B, "v60,v62,v65,v66" },
2211     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or, "v60,v62,v65,v66" },
2212     { Hexagon::BI__builtin_HEXAGON_V6_veqb_or_128B, "v60,v62,v65,v66" },
2213     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor, "v60,v62,v65,v66" },
2214     { Hexagon::BI__builtin_HEXAGON_V6_veqb_xor_128B, "v60,v62,v65,v66" },
2215     { Hexagon::BI__builtin_HEXAGON_V6_veqh, "v60,v62,v65,v66" },
2216     { Hexagon::BI__builtin_HEXAGON_V6_veqh_128B, "v60,v62,v65,v66" },
2217     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and, "v60,v62,v65,v66" },
2218     { Hexagon::BI__builtin_HEXAGON_V6_veqh_and_128B, "v60,v62,v65,v66" },
2219     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or, "v60,v62,v65,v66" },
2220     { Hexagon::BI__builtin_HEXAGON_V6_veqh_or_128B, "v60,v62,v65,v66" },
2221     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor, "v60,v62,v65,v66" },
2222     { Hexagon::BI__builtin_HEXAGON_V6_veqh_xor_128B, "v60,v62,v65,v66" },
2223     { Hexagon::BI__builtin_HEXAGON_V6_veqw, "v60,v62,v65,v66" },
2224     { Hexagon::BI__builtin_HEXAGON_V6_veqw_128B, "v60,v62,v65,v66" },
2225     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and, "v60,v62,v65,v66" },
2226     { Hexagon::BI__builtin_HEXAGON_V6_veqw_and_128B, "v60,v62,v65,v66" },
2227     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or, "v60,v62,v65,v66" },
2228     { Hexagon::BI__builtin_HEXAGON_V6_veqw_or_128B, "v60,v62,v65,v66" },
2229     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor, "v60,v62,v65,v66" },
2230     { Hexagon::BI__builtin_HEXAGON_V6_veqw_xor_128B, "v60,v62,v65,v66" },
2231     { Hexagon::BI__builtin_HEXAGON_V6_vgtb, "v60,v62,v65,v66" },
2232     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_128B, "v60,v62,v65,v66" },
2233     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and, "v60,v62,v65,v66" },
2234     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_and_128B, "v60,v62,v65,v66" },
2235     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or, "v60,v62,v65,v66" },
2236     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_or_128B, "v60,v62,v65,v66" },
2237     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor, "v60,v62,v65,v66" },
2238     { Hexagon::BI__builtin_HEXAGON_V6_vgtb_xor_128B, "v60,v62,v65,v66" },
2239     { Hexagon::BI__builtin_HEXAGON_V6_vgth, "v60,v62,v65,v66" },
2240     { Hexagon::BI__builtin_HEXAGON_V6_vgth_128B, "v60,v62,v65,v66" },
2241     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and, "v60,v62,v65,v66" },
2242     { Hexagon::BI__builtin_HEXAGON_V6_vgth_and_128B, "v60,v62,v65,v66" },
2243     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or, "v60,v62,v65,v66" },
2244     { Hexagon::BI__builtin_HEXAGON_V6_vgth_or_128B, "v60,v62,v65,v66" },
2245     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor, "v60,v62,v65,v66" },
2246     { Hexagon::BI__builtin_HEXAGON_V6_vgth_xor_128B, "v60,v62,v65,v66" },
2247     { Hexagon::BI__builtin_HEXAGON_V6_vgtub, "v60,v62,v65,v66" },
2248     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_128B, "v60,v62,v65,v66" },
2249     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and, "v60,v62,v65,v66" },
2250     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_and_128B, "v60,v62,v65,v66" },
2251     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or, "v60,v62,v65,v66" },
2252     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_or_128B, "v60,v62,v65,v66" },
2253     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor, "v60,v62,v65,v66" },
2254     { Hexagon::BI__builtin_HEXAGON_V6_vgtub_xor_128B, "v60,v62,v65,v66" },
2255     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh, "v60,v62,v65,v66" },
2256     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_128B, "v60,v62,v65,v66" },
2257     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and, "v60,v62,v65,v66" },
2258     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_and_128B, "v60,v62,v65,v66" },
2259     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or, "v60,v62,v65,v66" },
2260     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_or_128B, "v60,v62,v65,v66" },
2261     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor, "v60,v62,v65,v66" },
2262     { Hexagon::BI__builtin_HEXAGON_V6_vgtuh_xor_128B, "v60,v62,v65,v66" },
2263     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw, "v60,v62,v65,v66" },
2264     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_128B, "v60,v62,v65,v66" },
2265     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and, "v60,v62,v65,v66" },
2266     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_and_128B, "v60,v62,v65,v66" },
2267     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or, "v60,v62,v65,v66" },
2268     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_or_128B, "v60,v62,v65,v66" },
2269     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor, "v60,v62,v65,v66" },
2270     { Hexagon::BI__builtin_HEXAGON_V6_vgtuw_xor_128B, "v60,v62,v65,v66" },
2271     { Hexagon::BI__builtin_HEXAGON_V6_vgtw, "v60,v62,v65,v66" },
2272     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_128B, "v60,v62,v65,v66" },
2273     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and, "v60,v62,v65,v66" },
2274     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_and_128B, "v60,v62,v65,v66" },
2275     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or, "v60,v62,v65,v66" },
2276     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_or_128B, "v60,v62,v65,v66" },
2277     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor, "v60,v62,v65,v66" },
2278     { Hexagon::BI__builtin_HEXAGON_V6_vgtw_xor_128B, "v60,v62,v65,v66" },
2279     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr, "v60,v62,v65,v66" },
2280     { Hexagon::BI__builtin_HEXAGON_V6_vinsertwr_128B, "v60,v62,v65,v66" },
2281     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb, "v60,v62,v65,v66" },
2282     { Hexagon::BI__builtin_HEXAGON_V6_vlalignb_128B, "v60,v62,v65,v66" },
2283     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, "v60,v62,v65,v66" },
2284     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, "v60,v62,v65,v66" },
2285     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb, "v62,v65,v66" },
2286     { Hexagon::BI__builtin_HEXAGON_V6_vlsrb_128B, "v62,v65,v66" },
2287     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh, "v60,v62,v65,v66" },
2288     { Hexagon::BI__builtin_HEXAGON_V6_vlsrh_128B, "v60,v62,v65,v66" },
2289     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv, "v60,v62,v65,v66" },
2290     { Hexagon::BI__builtin_HEXAGON_V6_vlsrhv_128B, "v60,v62,v65,v66" },
2291     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw, "v60,v62,v65,v66" },
2292     { Hexagon::BI__builtin_HEXAGON_V6_vlsrw_128B, "v60,v62,v65,v66" },
2293     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv, "v60,v62,v65,v66" },
2294     { Hexagon::BI__builtin_HEXAGON_V6_vlsrwv_128B, "v60,v62,v65,v66" },
2295     { Hexagon::BI__builtin_HEXAGON_V6_vlut4, "v65,v66" },
2296     { Hexagon::BI__builtin_HEXAGON_V6_vlut4_128B, "v65,v66" },
2297     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb, "v60,v62,v65,v66" },
2298     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_128B, "v60,v62,v65,v66" },
2299     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi, "v62,v65,v66" },
2300     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvbi_128B, "v62,v65,v66" },
2301     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm, "v62,v65,v66" },
2302     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_nm_128B, "v62,v65,v66" },
2303     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc, "v60,v62,v65,v66" },
2304     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracc_128B, "v60,v62,v65,v66" },
2305     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci, "v62,v65,v66" },
2306     { Hexagon::BI__builtin_HEXAGON_V6_vlutvvb_oracci_128B, "v62,v65,v66" },
2307     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh, "v60,v62,v65,v66" },
2308     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_128B, "v60,v62,v65,v66" },
2309     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi, "v62,v65,v66" },
2310     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwhi_128B, "v62,v65,v66" },
2311     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm, "v62,v65,v66" },
2312     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_nm_128B, "v62,v65,v66" },
2313     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc, "v60,v62,v65,v66" },
2314     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracc_128B, "v60,v62,v65,v66" },
2315     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci, "v62,v65,v66" },
2316     { Hexagon::BI__builtin_HEXAGON_V6_vlutvwh_oracci_128B, "v62,v65,v66" },
2317     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb, "v62,v65,v66" },
2318     { Hexagon::BI__builtin_HEXAGON_V6_vmaxb_128B, "v62,v65,v66" },
2319     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh, "v60,v62,v65,v66" },
2320     { Hexagon::BI__builtin_HEXAGON_V6_vmaxh_128B, "v60,v62,v65,v66" },
2321     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub, "v60,v62,v65,v66" },
2322     { Hexagon::BI__builtin_HEXAGON_V6_vmaxub_128B, "v60,v62,v65,v66" },
2323     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh, "v60,v62,v65,v66" },
2324     { Hexagon::BI__builtin_HEXAGON_V6_vmaxuh_128B, "v60,v62,v65,v66" },
2325     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw, "v60,v62,v65,v66" },
2326     { Hexagon::BI__builtin_HEXAGON_V6_vmaxw_128B, "v60,v62,v65,v66" },
2327     { Hexagon::BI__builtin_HEXAGON_V6_vminb, "v62,v65,v66" },
2328     { Hexagon::BI__builtin_HEXAGON_V6_vminb_128B, "v62,v65,v66" },
2329     { Hexagon::BI__builtin_HEXAGON_V6_vminh, "v60,v62,v65,v66" },
2330     { Hexagon::BI__builtin_HEXAGON_V6_vminh_128B, "v60,v62,v65,v66" },
2331     { Hexagon::BI__builtin_HEXAGON_V6_vminub, "v60,v62,v65,v66" },
2332     { Hexagon::BI__builtin_HEXAGON_V6_vminub_128B, "v60,v62,v65,v66" },
2333     { Hexagon::BI__builtin_HEXAGON_V6_vminuh, "v60,v62,v65,v66" },
2334     { Hexagon::BI__builtin_HEXAGON_V6_vminuh_128B, "v60,v62,v65,v66" },
2335     { Hexagon::BI__builtin_HEXAGON_V6_vminw, "v60,v62,v65,v66" },
2336     { Hexagon::BI__builtin_HEXAGON_V6_vminw_128B, "v60,v62,v65,v66" },
2337     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus, "v60,v62,v65,v66" },
2338     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_128B, "v60,v62,v65,v66" },
2339     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc, "v60,v62,v65,v66" },
2340     { Hexagon::BI__builtin_HEXAGON_V6_vmpabus_acc_128B, "v60,v62,v65,v66" },
2341     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv, "v60,v62,v65,v66" },
2342     { Hexagon::BI__builtin_HEXAGON_V6_vmpabusv_128B, "v60,v62,v65,v66" },
2343     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu, "v65,v66" },
2344     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_128B, "v65,v66" },
2345     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc, "v65,v66" },
2346     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuu_acc_128B, "v65,v66" },
2347     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv, "v60,v62,v65,v66" },
2348     { Hexagon::BI__builtin_HEXAGON_V6_vmpabuuv_128B, "v60,v62,v65,v66" },
2349     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb, "v60,v62,v65,v66" },
2350     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_128B, "v60,v62,v65,v66" },
2351     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc, "v60,v62,v65,v66" },
2352     { Hexagon::BI__builtin_HEXAGON_V6_vmpahb_acc_128B, "v60,v62,v65,v66" },
2353     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat, "v65,v66" },
2354     { Hexagon::BI__builtin_HEXAGON_V6_vmpahhsat_128B, "v65,v66" },
2355     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb, "v62,v65,v66" },
2356     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_128B, "v62,v65,v66" },
2357     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc, "v62,v65,v66" },
2358     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhb_acc_128B, "v62,v65,v66" },
2359     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat, "v65,v66" },
2360     { Hexagon::BI__builtin_HEXAGON_V6_vmpauhuhsat_128B, "v65,v66" },
2361     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat, "v65,v66" },
2362     { Hexagon::BI__builtin_HEXAGON_V6_vmpsuhuhsat_128B, "v65,v66" },
2363     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus, "v60,v62,v65,v66" },
2364     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_128B, "v60,v62,v65,v66" },
2365     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc, "v60,v62,v65,v66" },
2366     { Hexagon::BI__builtin_HEXAGON_V6_vmpybus_acc_128B, "v60,v62,v65,v66" },
2367     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv, "v60,v62,v65,v66" },
2368     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_128B, "v60,v62,v65,v66" },
2369     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc, "v60,v62,v65,v66" },
2370     { Hexagon::BI__builtin_HEXAGON_V6_vmpybusv_acc_128B, "v60,v62,v65,v66" },
2371     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv, "v60,v62,v65,v66" },
2372     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_128B, "v60,v62,v65,v66" },
2373     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc, "v60,v62,v65,v66" },
2374     { Hexagon::BI__builtin_HEXAGON_V6_vmpybv_acc_128B, "v60,v62,v65,v66" },
2375     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh, "v60,v62,v65,v66" },
2376     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_128B, "v60,v62,v65,v66" },
2377     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64, "v62,v65,v66" },
2378     { Hexagon::BI__builtin_HEXAGON_V6_vmpyewuh_64_128B, "v62,v65,v66" },
2379     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh, "v60,v62,v65,v66" },
2380     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_128B, "v60,v62,v65,v66" },
2381     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc, "v65,v66" },
2382     { Hexagon::BI__builtin_HEXAGON_V6_vmpyh_acc_128B, "v65,v66" },
2383     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc, "v60,v62,v65,v66" },
2384     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsat_acc_128B, "v60,v62,v65,v66" },
2385     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs, "v60,v62,v65,v66" },
2386     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhsrs_128B, "v60,v62,v65,v66" },
2387     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss, "v60,v62,v65,v66" },
2388     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhss_128B, "v60,v62,v65,v66" },
2389     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus, "v60,v62,v65,v66" },
2390     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_128B, "v60,v62,v65,v66" },
2391     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc, "v60,v62,v65,v66" },
2392     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhus_acc_128B, "v60,v62,v65,v66" },
2393     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv, "v60,v62,v65,v66" },
2394     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_128B, "v60,v62,v65,v66" },
2395     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc, "v60,v62,v65,v66" },
2396     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhv_acc_128B, "v60,v62,v65,v66" },
2397     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs, "v60,v62,v65,v66" },
2398     { Hexagon::BI__builtin_HEXAGON_V6_vmpyhvsrs_128B, "v60,v62,v65,v66" },
2399     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh, "v60,v62,v65,v66" },
2400     { Hexagon::BI__builtin_HEXAGON_V6_vmpyieoh_128B, "v60,v62,v65,v66" },
2401     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc, "v60,v62,v65,v66" },
2402     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewh_acc_128B, "v60,v62,v65,v66" },
2403     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh, "v60,v62,v65,v66" },
2404     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_128B, "v60,v62,v65,v66" },
2405     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc, "v60,v62,v65,v66" },
2406     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiewuh_acc_128B, "v60,v62,v65,v66" },
2407     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih, "v60,v62,v65,v66" },
2408     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_128B, "v60,v62,v65,v66" },
2409     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc, "v60,v62,v65,v66" },
2410     { Hexagon::BI__builtin_HEXAGON_V6_vmpyih_acc_128B, "v60,v62,v65,v66" },
2411     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb, "v60,v62,v65,v66" },
2412     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_128B, "v60,v62,v65,v66" },
2413     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc, "v60,v62,v65,v66" },
2414     { Hexagon::BI__builtin_HEXAGON_V6_vmpyihb_acc_128B, "v60,v62,v65,v66" },
2415     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh, "v60,v62,v65,v66" },
2416     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiowh_128B, "v60,v62,v65,v66" },
2417     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb, "v60,v62,v65,v66" },
2418     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_128B, "v60,v62,v65,v66" },
2419     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc, "v60,v62,v65,v66" },
2420     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwb_acc_128B, "v60,v62,v65,v66" },
2421     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh, "v60,v62,v65,v66" },
2422     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_128B, "v60,v62,v65,v66" },
2423     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc, "v60,v62,v65,v66" },
2424     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwh_acc_128B, "v60,v62,v65,v66" },
2425     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub, "v62,v65,v66" },
2426     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_128B, "v62,v65,v66" },
2427     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc, "v62,v65,v66" },
2428     { Hexagon::BI__builtin_HEXAGON_V6_vmpyiwub_acc_128B, "v62,v65,v66" },
2429     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh, "v60,v62,v65,v66" },
2430     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_128B, "v60,v62,v65,v66" },
2431     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc, "v62,v65,v66" },
2432     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_64_acc_128B, "v62,v65,v66" },
2433     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd, "v60,v62,v65,v66" },
2434     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_128B, "v60,v62,v65,v66" },
2435     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc, "v60,v62,v65,v66" },
2436     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_rnd_sacc_128B, "v60,v62,v65,v66" },
2437     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc, "v60,v62,v65,v66" },
2438     { Hexagon::BI__builtin_HEXAGON_V6_vmpyowh_sacc_128B, "v60,v62,v65,v66" },
2439     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub, "v60,v62,v65,v66" },
2440     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_128B, "v60,v62,v65,v66" },
2441     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc, "v60,v62,v65,v66" },
2442     { Hexagon::BI__builtin_HEXAGON_V6_vmpyub_acc_128B, "v60,v62,v65,v66" },
2443     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv, "v60,v62,v65,v66" },
2444     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_128B, "v60,v62,v65,v66" },
2445     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc, "v60,v62,v65,v66" },
2446     { Hexagon::BI__builtin_HEXAGON_V6_vmpyubv_acc_128B, "v60,v62,v65,v66" },
2447     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh, "v60,v62,v65,v66" },
2448     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_128B, "v60,v62,v65,v66" },
2449     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc, "v60,v62,v65,v66" },
2450     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuh_acc_128B, "v60,v62,v65,v66" },
2451     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe, "v65,v66" },
2452     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_128B, "v65,v66" },
2453     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc, "v65,v66" },
2454     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhe_acc_128B, "v65,v66" },
2455     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv, "v60,v62,v65,v66" },
2456     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_128B, "v60,v62,v65,v66" },
2457     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc, "v60,v62,v65,v66" },
2458     { Hexagon::BI__builtin_HEXAGON_V6_vmpyuhv_acc_128B, "v60,v62,v65,v66" },
2459     { Hexagon::BI__builtin_HEXAGON_V6_vmux, "v60,v62,v65,v66" },
2460     { Hexagon::BI__builtin_HEXAGON_V6_vmux_128B, "v60,v62,v65,v66" },
2461     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb, "v65,v66" },
2462     { Hexagon::BI__builtin_HEXAGON_V6_vnavgb_128B, "v65,v66" },
2463     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh, "v60,v62,v65,v66" },
2464     { Hexagon::BI__builtin_HEXAGON_V6_vnavgh_128B, "v60,v62,v65,v66" },
2465     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub, "v60,v62,v65,v66" },
2466     { Hexagon::BI__builtin_HEXAGON_V6_vnavgub_128B, "v60,v62,v65,v66" },
2467     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw, "v60,v62,v65,v66" },
2468     { Hexagon::BI__builtin_HEXAGON_V6_vnavgw_128B, "v60,v62,v65,v66" },
2469     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth, "v60,v62,v65,v66" },
2470     { Hexagon::BI__builtin_HEXAGON_V6_vnormamth_128B, "v60,v62,v65,v66" },
2471     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw, "v60,v62,v65,v66" },
2472     { Hexagon::BI__builtin_HEXAGON_V6_vnormamtw_128B, "v60,v62,v65,v66" },
2473     { Hexagon::BI__builtin_HEXAGON_V6_vnot, "v60,v62,v65,v66" },
2474     { Hexagon::BI__builtin_HEXAGON_V6_vnot_128B, "v60,v62,v65,v66" },
2475     { Hexagon::BI__builtin_HEXAGON_V6_vor, "v60,v62,v65,v66" },
2476     { Hexagon::BI__builtin_HEXAGON_V6_vor_128B, "v60,v62,v65,v66" },
2477     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb, "v60,v62,v65,v66" },
2478     { Hexagon::BI__builtin_HEXAGON_V6_vpackeb_128B, "v60,v62,v65,v66" },
2479     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh, "v60,v62,v65,v66" },
2480     { Hexagon::BI__builtin_HEXAGON_V6_vpackeh_128B, "v60,v62,v65,v66" },
2481     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat, "v60,v62,v65,v66" },
2482     { Hexagon::BI__builtin_HEXAGON_V6_vpackhb_sat_128B, "v60,v62,v65,v66" },
2483     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat, "v60,v62,v65,v66" },
2484     { Hexagon::BI__builtin_HEXAGON_V6_vpackhub_sat_128B, "v60,v62,v65,v66" },
2485     { Hexagon::BI__builtin_HEXAGON_V6_vpackob, "v60,v62,v65,v66" },
2486     { Hexagon::BI__builtin_HEXAGON_V6_vpackob_128B, "v60,v62,v65,v66" },
2487     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh, "v60,v62,v65,v66" },
2488     { Hexagon::BI__builtin_HEXAGON_V6_vpackoh_128B, "v60,v62,v65,v66" },
2489     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat, "v60,v62,v65,v66" },
2490     { Hexagon::BI__builtin_HEXAGON_V6_vpackwh_sat_128B, "v60,v62,v65,v66" },
2491     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat, "v60,v62,v65,v66" },
2492     { Hexagon::BI__builtin_HEXAGON_V6_vpackwuh_sat_128B, "v60,v62,v65,v66" },
2493     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth, "v60,v62,v65,v66" },
2494     { Hexagon::BI__builtin_HEXAGON_V6_vpopcounth_128B, "v60,v62,v65,v66" },
2495     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb, "v65,v66" },
2496     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqb_128B, "v65,v66" },
2497     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh, "v65,v66" },
2498     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqh_128B, "v65,v66" },
2499     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw, "v65,v66" },
2500     { Hexagon::BI__builtin_HEXAGON_V6_vprefixqw_128B, "v65,v66" },
2501     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta, "v60,v62,v65,v66" },
2502     { Hexagon::BI__builtin_HEXAGON_V6_vrdelta_128B, "v60,v62,v65,v66" },
2503     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt, "v65" },
2504     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_128B, "v65" },
2505     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc, "v65" },
2506     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybub_rtt_acc_128B, "v65" },
2507     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus, "v60,v62,v65,v66" },
2508     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_128B, "v60,v62,v65,v66" },
2509     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc, "v60,v62,v65,v66" },
2510     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybus_acc_128B, "v60,v62,v65,v66" },
2511     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, "v60,v62,v65,v66" },
2512     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, "v60,v62,v65,v66" },
2513     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, "v60,v62,v65,v66" },
2514     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, "v60,v62,v65,v66" },
2515     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv, "v60,v62,v65,v66" },
2516     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_128B, "v60,v62,v65,v66" },
2517     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc, "v60,v62,v65,v66" },
2518     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusv_acc_128B, "v60,v62,v65,v66" },
2519     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv, "v60,v62,v65,v66" },
2520     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_128B, "v60,v62,v65,v66" },
2521     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc, "v60,v62,v65,v66" },
2522     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybv_acc_128B, "v60,v62,v65,v66" },
2523     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub, "v60,v62,v65,v66" },
2524     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_128B, "v60,v62,v65,v66" },
2525     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc, "v60,v62,v65,v66" },
2526     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_acc_128B, "v60,v62,v65,v66" },
2527     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, "v60,v62,v65,v66" },
2528     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, "v60,v62,v65,v66" },
2529     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, "v60,v62,v65,v66" },
2530     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, "v60,v62,v65,v66" },
2531     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt, "v65" },
2532     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_128B, "v65" },
2533     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc, "v65" },
2534     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyub_rtt_acc_128B, "v65" },
2535     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv, "v60,v62,v65,v66" },
2536     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_128B, "v60,v62,v65,v66" },
2537     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc, "v60,v62,v65,v66" },
2538     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubv_acc_128B, "v60,v62,v65,v66" },
2539     { Hexagon::BI__builtin_HEXAGON_V6_vror, "v60,v62,v65,v66" },
2540     { Hexagon::BI__builtin_HEXAGON_V6_vror_128B, "v60,v62,v65,v66" },
2541     { Hexagon::BI__builtin_HEXAGON_V6_vrotr, "v66" },
2542     { Hexagon::BI__builtin_HEXAGON_V6_vrotr_128B, "v66" },
2543     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb, "v60,v62,v65,v66" },
2544     { Hexagon::BI__builtin_HEXAGON_V6_vroundhb_128B, "v60,v62,v65,v66" },
2545     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub, "v60,v62,v65,v66" },
2546     { Hexagon::BI__builtin_HEXAGON_V6_vroundhub_128B, "v60,v62,v65,v66" },
2547     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub, "v62,v65,v66" },
2548     { Hexagon::BI__builtin_HEXAGON_V6_vrounduhub_128B, "v62,v65,v66" },
2549     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh, "v62,v65,v66" },
2550     { Hexagon::BI__builtin_HEXAGON_V6_vrounduwuh_128B, "v62,v65,v66" },
2551     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh, "v60,v62,v65,v66" },
2552     { Hexagon::BI__builtin_HEXAGON_V6_vroundwh_128B, "v60,v62,v65,v66" },
2553     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh, "v60,v62,v65,v66" },
2554     { Hexagon::BI__builtin_HEXAGON_V6_vroundwuh_128B, "v60,v62,v65,v66" },
2555     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, "v60,v62,v65,v66" },
2556     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, "v60,v62,v65,v66" },
2557     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, "v60,v62,v65,v66" },
2558     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, "v60,v62,v65,v66" },
2559     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw, "v66" },
2560     { Hexagon::BI__builtin_HEXAGON_V6_vsatdw_128B, "v66" },
2561     { Hexagon::BI__builtin_HEXAGON_V6_vsathub, "v60,v62,v65,v66" },
2562     { Hexagon::BI__builtin_HEXAGON_V6_vsathub_128B, "v60,v62,v65,v66" },
2563     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh, "v62,v65,v66" },
2564     { Hexagon::BI__builtin_HEXAGON_V6_vsatuwuh_128B, "v62,v65,v66" },
2565     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh, "v60,v62,v65,v66" },
2566     { Hexagon::BI__builtin_HEXAGON_V6_vsatwh_128B, "v60,v62,v65,v66" },
2567     { Hexagon::BI__builtin_HEXAGON_V6_vsb, "v60,v62,v65,v66" },
2568     { Hexagon::BI__builtin_HEXAGON_V6_vsb_128B, "v60,v62,v65,v66" },
2569     { Hexagon::BI__builtin_HEXAGON_V6_vsh, "v60,v62,v65,v66" },
2570     { Hexagon::BI__builtin_HEXAGON_V6_vsh_128B, "v60,v62,v65,v66" },
2571     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh, "v60,v62,v65,v66" },
2572     { Hexagon::BI__builtin_HEXAGON_V6_vshufeh_128B, "v60,v62,v65,v66" },
2573     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb, "v60,v62,v65,v66" },
2574     { Hexagon::BI__builtin_HEXAGON_V6_vshuffb_128B, "v60,v62,v65,v66" },
2575     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb, "v60,v62,v65,v66" },
2576     { Hexagon::BI__builtin_HEXAGON_V6_vshuffeb_128B, "v60,v62,v65,v66" },
2577     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh, "v60,v62,v65,v66" },
2578     { Hexagon::BI__builtin_HEXAGON_V6_vshuffh_128B, "v60,v62,v65,v66" },
2579     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob, "v60,v62,v65,v66" },
2580     { Hexagon::BI__builtin_HEXAGON_V6_vshuffob_128B, "v60,v62,v65,v66" },
2581     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd, "v60,v62,v65,v66" },
2582     { Hexagon::BI__builtin_HEXAGON_V6_vshuffvdd_128B, "v60,v62,v65,v66" },
2583     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb, "v60,v62,v65,v66" },
2584     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeb_128B, "v60,v62,v65,v66" },
2585     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh, "v60,v62,v65,v66" },
2586     { Hexagon::BI__builtin_HEXAGON_V6_vshufoeh_128B, "v60,v62,v65,v66" },
2587     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh, "v60,v62,v65,v66" },
2588     { Hexagon::BI__builtin_HEXAGON_V6_vshufoh_128B, "v60,v62,v65,v66" },
2589     { Hexagon::BI__builtin_HEXAGON_V6_vsubb, "v60,v62,v65,v66" },
2590     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_128B, "v60,v62,v65,v66" },
2591     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv, "v60,v62,v65,v66" },
2592     { Hexagon::BI__builtin_HEXAGON_V6_vsubb_dv_128B, "v60,v62,v65,v66" },
2593     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat, "v62,v65,v66" },
2594     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_128B, "v62,v65,v66" },
2595     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv, "v62,v65,v66" },
2596     { Hexagon::BI__builtin_HEXAGON_V6_vsubbsat_dv_128B, "v62,v65,v66" },
2597     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry, "v62,v65,v66" },
2598     { Hexagon::BI__builtin_HEXAGON_V6_vsubcarry_128B, "v62,v65,v66" },
2599     { Hexagon::BI__builtin_HEXAGON_V6_vsubh, "v60,v62,v65,v66" },
2600     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_128B, "v60,v62,v65,v66" },
2601     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv, "v60,v62,v65,v66" },
2602     { Hexagon::BI__builtin_HEXAGON_V6_vsubh_dv_128B, "v60,v62,v65,v66" },
2603     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat, "v60,v62,v65,v66" },
2604     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_128B, "v60,v62,v65,v66" },
2605     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv, "v60,v62,v65,v66" },
2606     { Hexagon::BI__builtin_HEXAGON_V6_vsubhsat_dv_128B, "v60,v62,v65,v66" },
2607     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw, "v60,v62,v65,v66" },
2608     { Hexagon::BI__builtin_HEXAGON_V6_vsubhw_128B, "v60,v62,v65,v66" },
2609     { Hexagon::BI__builtin_HEXAGON_V6_vsububh, "v60,v62,v65,v66" },
2610     { Hexagon::BI__builtin_HEXAGON_V6_vsububh_128B, "v60,v62,v65,v66" },
2611     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat, "v60,v62,v65,v66" },
2612     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_128B, "v60,v62,v65,v66" },
2613     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv, "v60,v62,v65,v66" },
2614     { Hexagon::BI__builtin_HEXAGON_V6_vsububsat_dv_128B, "v60,v62,v65,v66" },
2615     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat, "v62,v65,v66" },
2616     { Hexagon::BI__builtin_HEXAGON_V6_vsubububb_sat_128B, "v62,v65,v66" },
2617     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat, "v60,v62,v65,v66" },
2618     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_128B, "v60,v62,v65,v66" },
2619     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv, "v60,v62,v65,v66" },
2620     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhsat_dv_128B, "v60,v62,v65,v66" },
2621     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw, "v60,v62,v65,v66" },
2622     { Hexagon::BI__builtin_HEXAGON_V6_vsubuhw_128B, "v60,v62,v65,v66" },
2623     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat, "v62,v65,v66" },
2624     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_128B, "v62,v65,v66" },
2625     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv, "v62,v65,v66" },
2626     { Hexagon::BI__builtin_HEXAGON_V6_vsubuwsat_dv_128B, "v62,v65,v66" },
2627     { Hexagon::BI__builtin_HEXAGON_V6_vsubw, "v60,v62,v65,v66" },
2628     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_128B, "v60,v62,v65,v66" },
2629     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv, "v60,v62,v65,v66" },
2630     { Hexagon::BI__builtin_HEXAGON_V6_vsubw_dv_128B, "v60,v62,v65,v66" },
2631     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat, "v60,v62,v65,v66" },
2632     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_128B, "v60,v62,v65,v66" },
2633     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv, "v60,v62,v65,v66" },
2634     { Hexagon::BI__builtin_HEXAGON_V6_vsubwsat_dv_128B, "v60,v62,v65,v66" },
2635     { Hexagon::BI__builtin_HEXAGON_V6_vswap, "v60,v62,v65,v66" },
2636     { Hexagon::BI__builtin_HEXAGON_V6_vswap_128B, "v60,v62,v65,v66" },
2637     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb, "v60,v62,v65,v66" },
2638     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_128B, "v60,v62,v65,v66" },
2639     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc, "v60,v62,v65,v66" },
2640     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyb_acc_128B, "v60,v62,v65,v66" },
2641     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus, "v60,v62,v65,v66" },
2642     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_128B, "v60,v62,v65,v66" },
2643     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc, "v60,v62,v65,v66" },
2644     { Hexagon::BI__builtin_HEXAGON_V6_vtmpybus_acc_128B, "v60,v62,v65,v66" },
2645     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb, "v60,v62,v65,v66" },
2646     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_128B, "v60,v62,v65,v66" },
2647     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc, "v60,v62,v65,v66" },
2648     { Hexagon::BI__builtin_HEXAGON_V6_vtmpyhb_acc_128B, "v60,v62,v65,v66" },
2649     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb, "v60,v62,v65,v66" },
2650     { Hexagon::BI__builtin_HEXAGON_V6_vunpackb_128B, "v60,v62,v65,v66" },
2651     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh, "v60,v62,v65,v66" },
2652     { Hexagon::BI__builtin_HEXAGON_V6_vunpackh_128B, "v60,v62,v65,v66" },
2653     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob, "v60,v62,v65,v66" },
2654     { Hexagon::BI__builtin_HEXAGON_V6_vunpackob_128B, "v60,v62,v65,v66" },
2655     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh, "v60,v62,v65,v66" },
2656     { Hexagon::BI__builtin_HEXAGON_V6_vunpackoh_128B, "v60,v62,v65,v66" },
2657     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub, "v60,v62,v65,v66" },
2658     { Hexagon::BI__builtin_HEXAGON_V6_vunpackub_128B, "v60,v62,v65,v66" },
2659     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh, "v60,v62,v65,v66" },
2660     { Hexagon::BI__builtin_HEXAGON_V6_vunpackuh_128B, "v60,v62,v65,v66" },
2661     { Hexagon::BI__builtin_HEXAGON_V6_vxor, "v60,v62,v65,v66" },
2662     { Hexagon::BI__builtin_HEXAGON_V6_vxor_128B, "v60,v62,v65,v66" },
2663     { Hexagon::BI__builtin_HEXAGON_V6_vzb, "v60,v62,v65,v66" },
2664     { Hexagon::BI__builtin_HEXAGON_V6_vzb_128B, "v60,v62,v65,v66" },
2665     { Hexagon::BI__builtin_HEXAGON_V6_vzh, "v60,v62,v65,v66" },
2666     { Hexagon::BI__builtin_HEXAGON_V6_vzh_128B, "v60,v62,v65,v66" },
2667   };
2668 
2669   // Sort the tables on first execution so we can binary search them.
2670   auto SortCmp = [](const BuiltinAndString &LHS, const BuiltinAndString &RHS) {
2671     return LHS.BuiltinID < RHS.BuiltinID;
2672   };
2673   static const bool SortOnce =
2674       (llvm::sort(ValidCPU, SortCmp),
2675        llvm::sort(ValidHVX, SortCmp), true);
2676   (void)SortOnce;
2677   auto LowerBoundCmp = [](const BuiltinAndString &BI, unsigned BuiltinID) {
2678     return BI.BuiltinID < BuiltinID;
2679   };
2680 
2681   const TargetInfo &TI = Context.getTargetInfo();
2682 
2683   const BuiltinAndString *FC =
2684       std::lower_bound(std::begin(ValidCPU), std::end(ValidCPU), BuiltinID,
2685                        LowerBoundCmp);
2686   if (FC != std::end(ValidCPU) && FC->BuiltinID == BuiltinID) {
2687     const TargetOptions &Opts = TI.getTargetOpts();
2688     StringRef CPU = Opts.CPU;
2689     if (!CPU.empty()) {
2690       assert(CPU.startswith("hexagon") && "Unexpected CPU name");
2691       CPU.consume_front("hexagon");
2692       SmallVector<StringRef, 3> CPUs;
2693       StringRef(FC->Str).split(CPUs, ',');
2694       if (llvm::none_of(CPUs, [CPU](StringRef S) { return S == CPU; }))
2695         return Diag(TheCall->getBeginLoc(),
2696                     diag::err_hexagon_builtin_unsupported_cpu);
2697     }
2698   }
2699 
2700   const BuiltinAndString *FH =
2701       std::lower_bound(std::begin(ValidHVX), std::end(ValidHVX), BuiltinID,
2702                        LowerBoundCmp);
2703   if (FH != std::end(ValidHVX) && FH->BuiltinID == BuiltinID) {
2704     if (!TI.hasFeature("hvx"))
2705       return Diag(TheCall->getBeginLoc(),
2706                   diag::err_hexagon_builtin_requires_hvx);
2707 
2708     SmallVector<StringRef, 3> HVXs;
2709     StringRef(FH->Str).split(HVXs, ',');
2710     bool IsValid = llvm::any_of(HVXs,
2711                                 [&TI] (StringRef V) {
2712                                   std::string F = "hvx" + V.str();
2713                                   return TI.hasFeature(F);
2714                                 });
2715     if (!IsValid)
2716       return Diag(TheCall->getBeginLoc(),
2717                   diag::err_hexagon_builtin_unsupported_hvx);
2718   }
2719 
2720   return false;
2721 }
2722 
2723 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2724   struct ArgInfo {
2725     uint8_t OpNum;
2726     bool IsSigned;
2727     uint8_t BitWidth;
2728     uint8_t Align;
2729   };
2730   struct BuiltinInfo {
2731     unsigned BuiltinID;
2732     ArgInfo Infos[2];
2733   };
2734 
2735   static BuiltinInfo Infos[] = {
2736     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2737     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2738     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2739     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  0 }} },
2740     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2741     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2742     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2743     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2744     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2745     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2746     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2747 
2748     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2749     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2750     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2751     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2752     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2753     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2754     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2755     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2756     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2757     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2758     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2759 
2760     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2761     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2762     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2780     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2790     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2812                                                       {{ 1, false, 6,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2820                                                       {{ 1, false, 5,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2827                                                        { 2, false, 5,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2829                                                        { 2, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2831                                                        { 3, false, 5,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2833                                                        { 3, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2850                                                       {{ 2, false, 4,  0 },
2851                                                        { 3, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2853                                                       {{ 2, false, 4,  0 },
2854                                                        { 3, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2856                                                       {{ 2, false, 4,  0 },
2857                                                        { 3, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2859                                                       {{ 2, false, 4,  0 },
2860                                                        { 3, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2872                                                        { 2, false, 5,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2874                                                        { 2, false, 6,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2884                                                       {{ 1, false, 4,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2887                                                       {{ 1, false, 4,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2908                                                       {{ 3, false, 1,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2913                                                       {{ 3, false, 1,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2918                                                       {{ 3, false, 1,  0 }} },
2919   };
2920 
2921   // Use a dynamically initialized static to sort the table exactly once on
2922   // first run.
2923   static const bool SortOnce =
2924       (llvm::sort(Infos,
2925                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2926                    return LHS.BuiltinID < RHS.BuiltinID;
2927                  }),
2928        true);
2929   (void)SortOnce;
2930 
2931   const BuiltinInfo *F =
2932       std::lower_bound(std::begin(Infos), std::end(Infos), BuiltinID,
2933                        [](const BuiltinInfo &BI, unsigned BuiltinID) {
2934                          return BI.BuiltinID < BuiltinID;
2935                        });
2936   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2937     return false;
2938 
2939   bool Error = false;
2940 
2941   for (const ArgInfo &A : F->Infos) {
2942     // Ignore empty ArgInfo elements.
2943     if (A.BitWidth == 0)
2944       continue;
2945 
2946     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2947     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2948     if (!A.Align) {
2949       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2950     } else {
2951       unsigned M = 1 << A.Align;
2952       Min *= M;
2953       Max *= M;
2954       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2955                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2956     }
2957   }
2958   return Error;
2959 }
2960 
2961 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2962                                            CallExpr *TheCall) {
2963   return CheckHexagonBuiltinCpu(BuiltinID, TheCall) ||
2964          CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2965 }
2966 
2967 
2968 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
2969 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2970 // ordering for DSP is unspecified. MSA is ordered by the data format used
2971 // by the underlying instruction i.e., df/m, df/n and then by size.
2972 //
2973 // FIXME: The size tests here should instead be tablegen'd along with the
2974 //        definitions from include/clang/Basic/BuiltinsMips.def.
2975 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2976 //        be too.
2977 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2978   unsigned i = 0, l = 0, u = 0, m = 0;
2979   switch (BuiltinID) {
2980   default: return false;
2981   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2982   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2983   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
2984   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
2985   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
2986   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
2987   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
2988   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
2989   // df/m field.
2990   // These intrinsics take an unsigned 3 bit immediate.
2991   case Mips::BI__builtin_msa_bclri_b:
2992   case Mips::BI__builtin_msa_bnegi_b:
2993   case Mips::BI__builtin_msa_bseti_b:
2994   case Mips::BI__builtin_msa_sat_s_b:
2995   case Mips::BI__builtin_msa_sat_u_b:
2996   case Mips::BI__builtin_msa_slli_b:
2997   case Mips::BI__builtin_msa_srai_b:
2998   case Mips::BI__builtin_msa_srari_b:
2999   case Mips::BI__builtin_msa_srli_b:
3000   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3001   case Mips::BI__builtin_msa_binsli_b:
3002   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3003   // These intrinsics take an unsigned 4 bit immediate.
3004   case Mips::BI__builtin_msa_bclri_h:
3005   case Mips::BI__builtin_msa_bnegi_h:
3006   case Mips::BI__builtin_msa_bseti_h:
3007   case Mips::BI__builtin_msa_sat_s_h:
3008   case Mips::BI__builtin_msa_sat_u_h:
3009   case Mips::BI__builtin_msa_slli_h:
3010   case Mips::BI__builtin_msa_srai_h:
3011   case Mips::BI__builtin_msa_srari_h:
3012   case Mips::BI__builtin_msa_srli_h:
3013   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3014   case Mips::BI__builtin_msa_binsli_h:
3015   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3016   // These intrinsics take an unsigned 5 bit immediate.
3017   // The first block of intrinsics actually have an unsigned 5 bit field,
3018   // not a df/n field.
3019   case Mips::BI__builtin_msa_clei_u_b:
3020   case Mips::BI__builtin_msa_clei_u_h:
3021   case Mips::BI__builtin_msa_clei_u_w:
3022   case Mips::BI__builtin_msa_clei_u_d:
3023   case Mips::BI__builtin_msa_clti_u_b:
3024   case Mips::BI__builtin_msa_clti_u_h:
3025   case Mips::BI__builtin_msa_clti_u_w:
3026   case Mips::BI__builtin_msa_clti_u_d:
3027   case Mips::BI__builtin_msa_maxi_u_b:
3028   case Mips::BI__builtin_msa_maxi_u_h:
3029   case Mips::BI__builtin_msa_maxi_u_w:
3030   case Mips::BI__builtin_msa_maxi_u_d:
3031   case Mips::BI__builtin_msa_mini_u_b:
3032   case Mips::BI__builtin_msa_mini_u_h:
3033   case Mips::BI__builtin_msa_mini_u_w:
3034   case Mips::BI__builtin_msa_mini_u_d:
3035   case Mips::BI__builtin_msa_addvi_b:
3036   case Mips::BI__builtin_msa_addvi_h:
3037   case Mips::BI__builtin_msa_addvi_w:
3038   case Mips::BI__builtin_msa_addvi_d:
3039   case Mips::BI__builtin_msa_bclri_w:
3040   case Mips::BI__builtin_msa_bnegi_w:
3041   case Mips::BI__builtin_msa_bseti_w:
3042   case Mips::BI__builtin_msa_sat_s_w:
3043   case Mips::BI__builtin_msa_sat_u_w:
3044   case Mips::BI__builtin_msa_slli_w:
3045   case Mips::BI__builtin_msa_srai_w:
3046   case Mips::BI__builtin_msa_srari_w:
3047   case Mips::BI__builtin_msa_srli_w:
3048   case Mips::BI__builtin_msa_srlri_w:
3049   case Mips::BI__builtin_msa_subvi_b:
3050   case Mips::BI__builtin_msa_subvi_h:
3051   case Mips::BI__builtin_msa_subvi_w:
3052   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3053   case Mips::BI__builtin_msa_binsli_w:
3054   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3055   // These intrinsics take an unsigned 6 bit immediate.
3056   case Mips::BI__builtin_msa_bclri_d:
3057   case Mips::BI__builtin_msa_bnegi_d:
3058   case Mips::BI__builtin_msa_bseti_d:
3059   case Mips::BI__builtin_msa_sat_s_d:
3060   case Mips::BI__builtin_msa_sat_u_d:
3061   case Mips::BI__builtin_msa_slli_d:
3062   case Mips::BI__builtin_msa_srai_d:
3063   case Mips::BI__builtin_msa_srari_d:
3064   case Mips::BI__builtin_msa_srli_d:
3065   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3066   case Mips::BI__builtin_msa_binsli_d:
3067   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3068   // These intrinsics take a signed 5 bit immediate.
3069   case Mips::BI__builtin_msa_ceqi_b:
3070   case Mips::BI__builtin_msa_ceqi_h:
3071   case Mips::BI__builtin_msa_ceqi_w:
3072   case Mips::BI__builtin_msa_ceqi_d:
3073   case Mips::BI__builtin_msa_clti_s_b:
3074   case Mips::BI__builtin_msa_clti_s_h:
3075   case Mips::BI__builtin_msa_clti_s_w:
3076   case Mips::BI__builtin_msa_clti_s_d:
3077   case Mips::BI__builtin_msa_clei_s_b:
3078   case Mips::BI__builtin_msa_clei_s_h:
3079   case Mips::BI__builtin_msa_clei_s_w:
3080   case Mips::BI__builtin_msa_clei_s_d:
3081   case Mips::BI__builtin_msa_maxi_s_b:
3082   case Mips::BI__builtin_msa_maxi_s_h:
3083   case Mips::BI__builtin_msa_maxi_s_w:
3084   case Mips::BI__builtin_msa_maxi_s_d:
3085   case Mips::BI__builtin_msa_mini_s_b:
3086   case Mips::BI__builtin_msa_mini_s_h:
3087   case Mips::BI__builtin_msa_mini_s_w:
3088   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3089   // These intrinsics take an unsigned 8 bit immediate.
3090   case Mips::BI__builtin_msa_andi_b:
3091   case Mips::BI__builtin_msa_nori_b:
3092   case Mips::BI__builtin_msa_ori_b:
3093   case Mips::BI__builtin_msa_shf_b:
3094   case Mips::BI__builtin_msa_shf_h:
3095   case Mips::BI__builtin_msa_shf_w:
3096   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3097   case Mips::BI__builtin_msa_bseli_b:
3098   case Mips::BI__builtin_msa_bmnzi_b:
3099   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3100   // df/n format
3101   // These intrinsics take an unsigned 4 bit immediate.
3102   case Mips::BI__builtin_msa_copy_s_b:
3103   case Mips::BI__builtin_msa_copy_u_b:
3104   case Mips::BI__builtin_msa_insve_b:
3105   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3106   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3107   // These intrinsics take an unsigned 3 bit immediate.
3108   case Mips::BI__builtin_msa_copy_s_h:
3109   case Mips::BI__builtin_msa_copy_u_h:
3110   case Mips::BI__builtin_msa_insve_h:
3111   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3112   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3113   // These intrinsics take an unsigned 2 bit immediate.
3114   case Mips::BI__builtin_msa_copy_s_w:
3115   case Mips::BI__builtin_msa_copy_u_w:
3116   case Mips::BI__builtin_msa_insve_w:
3117   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3118   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3119   // These intrinsics take an unsigned 1 bit immediate.
3120   case Mips::BI__builtin_msa_copy_s_d:
3121   case Mips::BI__builtin_msa_copy_u_d:
3122   case Mips::BI__builtin_msa_insve_d:
3123   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3124   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3125   // Memory offsets and immediate loads.
3126   // These intrinsics take a signed 10 bit immediate.
3127   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3128   case Mips::BI__builtin_msa_ldi_h:
3129   case Mips::BI__builtin_msa_ldi_w:
3130   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3131   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3132   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3133   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3134   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3135   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3136   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3137   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3138   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3139   }
3140 
3141   if (!m)
3142     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3143 
3144   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3145          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3146 }
3147 
3148 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3149   unsigned i = 0, l = 0, u = 0;
3150   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3151                       BuiltinID == PPC::BI__builtin_divdeu ||
3152                       BuiltinID == PPC::BI__builtin_bpermd;
3153   bool IsTarget64Bit = Context.getTargetInfo()
3154                               .getTypeWidth(Context
3155                                             .getTargetInfo()
3156                                             .getIntPtrType()) == 64;
3157   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3158                        BuiltinID == PPC::BI__builtin_divweu ||
3159                        BuiltinID == PPC::BI__builtin_divde ||
3160                        BuiltinID == PPC::BI__builtin_divdeu;
3161 
3162   if (Is64BitBltin && !IsTarget64Bit)
3163     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3164            << TheCall->getSourceRange();
3165 
3166   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
3167       (BuiltinID == PPC::BI__builtin_bpermd &&
3168        !Context.getTargetInfo().hasFeature("bpermd")))
3169     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3170            << TheCall->getSourceRange();
3171 
3172   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3173     if (!Context.getTargetInfo().hasFeature("vsx"))
3174       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3175              << TheCall->getSourceRange();
3176     return false;
3177   };
3178 
3179   switch (BuiltinID) {
3180   default: return false;
3181   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3182   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3183     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3184            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3185   case PPC::BI__builtin_tbegin:
3186   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3187   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3188   case PPC::BI__builtin_tabortwc:
3189   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3190   case PPC::BI__builtin_tabortwci:
3191   case PPC::BI__builtin_tabortdci:
3192     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3193            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3194   case PPC::BI__builtin_vsx_xxpermdi:
3195   case PPC::BI__builtin_vsx_xxsldwi:
3196     return SemaBuiltinVSX(TheCall);
3197   case PPC::BI__builtin_unpack_vector_int128:
3198     return SemaVSXCheck(TheCall) ||
3199            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3200   case PPC::BI__builtin_pack_vector_int128:
3201     return SemaVSXCheck(TheCall);
3202   }
3203   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3204 }
3205 
3206 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3207                                            CallExpr *TheCall) {
3208   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3209     Expr *Arg = TheCall->getArg(0);
3210     llvm::APSInt AbortCode(32);
3211     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
3212         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
3213       return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3214              << Arg->getSourceRange();
3215   }
3216 
3217   // For intrinsics which take an immediate value as part of the instruction,
3218   // range check them here.
3219   unsigned i = 0, l = 0, u = 0;
3220   switch (BuiltinID) {
3221   default: return false;
3222   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3223   case SystemZ::BI__builtin_s390_verimb:
3224   case SystemZ::BI__builtin_s390_verimh:
3225   case SystemZ::BI__builtin_s390_verimf:
3226   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3227   case SystemZ::BI__builtin_s390_vfaeb:
3228   case SystemZ::BI__builtin_s390_vfaeh:
3229   case SystemZ::BI__builtin_s390_vfaef:
3230   case SystemZ::BI__builtin_s390_vfaebs:
3231   case SystemZ::BI__builtin_s390_vfaehs:
3232   case SystemZ::BI__builtin_s390_vfaefs:
3233   case SystemZ::BI__builtin_s390_vfaezb:
3234   case SystemZ::BI__builtin_s390_vfaezh:
3235   case SystemZ::BI__builtin_s390_vfaezf:
3236   case SystemZ::BI__builtin_s390_vfaezbs:
3237   case SystemZ::BI__builtin_s390_vfaezhs:
3238   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3239   case SystemZ::BI__builtin_s390_vfisb:
3240   case SystemZ::BI__builtin_s390_vfidb:
3241     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3242            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3243   case SystemZ::BI__builtin_s390_vftcisb:
3244   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3245   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3246   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3247   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3248   case SystemZ::BI__builtin_s390_vstrcb:
3249   case SystemZ::BI__builtin_s390_vstrch:
3250   case SystemZ::BI__builtin_s390_vstrcf:
3251   case SystemZ::BI__builtin_s390_vstrczb:
3252   case SystemZ::BI__builtin_s390_vstrczh:
3253   case SystemZ::BI__builtin_s390_vstrczf:
3254   case SystemZ::BI__builtin_s390_vstrcbs:
3255   case SystemZ::BI__builtin_s390_vstrchs:
3256   case SystemZ::BI__builtin_s390_vstrcfs:
3257   case SystemZ::BI__builtin_s390_vstrczbs:
3258   case SystemZ::BI__builtin_s390_vstrczhs:
3259   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3260   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3261   case SystemZ::BI__builtin_s390_vfminsb:
3262   case SystemZ::BI__builtin_s390_vfmaxsb:
3263   case SystemZ::BI__builtin_s390_vfmindb:
3264   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3265   }
3266   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3267 }
3268 
3269 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3270 /// This checks that the target supports __builtin_cpu_supports and
3271 /// that the string argument is constant and valid.
3272 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
3273   Expr *Arg = TheCall->getArg(0);
3274 
3275   // Check if the argument is a string literal.
3276   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3277     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3278            << Arg->getSourceRange();
3279 
3280   // Check the contents of the string.
3281   StringRef Feature =
3282       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3283   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
3284     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3285            << Arg->getSourceRange();
3286   return false;
3287 }
3288 
3289 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3290 /// This checks that the target supports __builtin_cpu_is and
3291 /// that the string argument is constant and valid.
3292 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
3293   Expr *Arg = TheCall->getArg(0);
3294 
3295   // Check if the argument is a string literal.
3296   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3297     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3298            << Arg->getSourceRange();
3299 
3300   // Check the contents of the string.
3301   StringRef Feature =
3302       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3303   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
3304     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3305            << Arg->getSourceRange();
3306   return false;
3307 }
3308 
3309 // Check if the rounding mode is legal.
3310 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3311   // Indicates if this instruction has rounding control or just SAE.
3312   bool HasRC = false;
3313 
3314   unsigned ArgNum = 0;
3315   switch (BuiltinID) {
3316   default:
3317     return false;
3318   case X86::BI__builtin_ia32_vcvttsd2si32:
3319   case X86::BI__builtin_ia32_vcvttsd2si64:
3320   case X86::BI__builtin_ia32_vcvttsd2usi32:
3321   case X86::BI__builtin_ia32_vcvttsd2usi64:
3322   case X86::BI__builtin_ia32_vcvttss2si32:
3323   case X86::BI__builtin_ia32_vcvttss2si64:
3324   case X86::BI__builtin_ia32_vcvttss2usi32:
3325   case X86::BI__builtin_ia32_vcvttss2usi64:
3326     ArgNum = 1;
3327     break;
3328   case X86::BI__builtin_ia32_maxpd512:
3329   case X86::BI__builtin_ia32_maxps512:
3330   case X86::BI__builtin_ia32_minpd512:
3331   case X86::BI__builtin_ia32_minps512:
3332     ArgNum = 2;
3333     break;
3334   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3335   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3336   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3337   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3338   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3339   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3340   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3341   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3342   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3343   case X86::BI__builtin_ia32_exp2pd_mask:
3344   case X86::BI__builtin_ia32_exp2ps_mask:
3345   case X86::BI__builtin_ia32_getexppd512_mask:
3346   case X86::BI__builtin_ia32_getexpps512_mask:
3347   case X86::BI__builtin_ia32_rcp28pd_mask:
3348   case X86::BI__builtin_ia32_rcp28ps_mask:
3349   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3350   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3351   case X86::BI__builtin_ia32_vcomisd:
3352   case X86::BI__builtin_ia32_vcomiss:
3353   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3354     ArgNum = 3;
3355     break;
3356   case X86::BI__builtin_ia32_cmppd512_mask:
3357   case X86::BI__builtin_ia32_cmpps512_mask:
3358   case X86::BI__builtin_ia32_cmpsd_mask:
3359   case X86::BI__builtin_ia32_cmpss_mask:
3360   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3361   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3362   case X86::BI__builtin_ia32_getexpss128_round_mask:
3363   case X86::BI__builtin_ia32_maxsd_round_mask:
3364   case X86::BI__builtin_ia32_maxss_round_mask:
3365   case X86::BI__builtin_ia32_minsd_round_mask:
3366   case X86::BI__builtin_ia32_minss_round_mask:
3367   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3368   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3369   case X86::BI__builtin_ia32_reducepd512_mask:
3370   case X86::BI__builtin_ia32_reduceps512_mask:
3371   case X86::BI__builtin_ia32_rndscalepd_mask:
3372   case X86::BI__builtin_ia32_rndscaleps_mask:
3373   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3374   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3375     ArgNum = 4;
3376     break;
3377   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3378   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3379   case X86::BI__builtin_ia32_fixupimmps512_mask:
3380   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3381   case X86::BI__builtin_ia32_fixupimmsd_mask:
3382   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3383   case X86::BI__builtin_ia32_fixupimmss_mask:
3384   case X86::BI__builtin_ia32_fixupimmss_maskz:
3385   case X86::BI__builtin_ia32_rangepd512_mask:
3386   case X86::BI__builtin_ia32_rangeps512_mask:
3387   case X86::BI__builtin_ia32_rangesd128_round_mask:
3388   case X86::BI__builtin_ia32_rangess128_round_mask:
3389   case X86::BI__builtin_ia32_reducesd_mask:
3390   case X86::BI__builtin_ia32_reducess_mask:
3391   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3392   case X86::BI__builtin_ia32_rndscaless_round_mask:
3393     ArgNum = 5;
3394     break;
3395   case X86::BI__builtin_ia32_vcvtsd2si64:
3396   case X86::BI__builtin_ia32_vcvtsd2si32:
3397   case X86::BI__builtin_ia32_vcvtsd2usi32:
3398   case X86::BI__builtin_ia32_vcvtsd2usi64:
3399   case X86::BI__builtin_ia32_vcvtss2si32:
3400   case X86::BI__builtin_ia32_vcvtss2si64:
3401   case X86::BI__builtin_ia32_vcvtss2usi32:
3402   case X86::BI__builtin_ia32_vcvtss2usi64:
3403   case X86::BI__builtin_ia32_sqrtpd512:
3404   case X86::BI__builtin_ia32_sqrtps512:
3405     ArgNum = 1;
3406     HasRC = true;
3407     break;
3408   case X86::BI__builtin_ia32_addpd512:
3409   case X86::BI__builtin_ia32_addps512:
3410   case X86::BI__builtin_ia32_divpd512:
3411   case X86::BI__builtin_ia32_divps512:
3412   case X86::BI__builtin_ia32_mulpd512:
3413   case X86::BI__builtin_ia32_mulps512:
3414   case X86::BI__builtin_ia32_subpd512:
3415   case X86::BI__builtin_ia32_subps512:
3416   case X86::BI__builtin_ia32_cvtsi2sd64:
3417   case X86::BI__builtin_ia32_cvtsi2ss32:
3418   case X86::BI__builtin_ia32_cvtsi2ss64:
3419   case X86::BI__builtin_ia32_cvtusi2sd64:
3420   case X86::BI__builtin_ia32_cvtusi2ss32:
3421   case X86::BI__builtin_ia32_cvtusi2ss64:
3422     ArgNum = 2;
3423     HasRC = true;
3424     break;
3425   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3426   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3427   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3428   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3429   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3430   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3431   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3432   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3433   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3434   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3435   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3436     ArgNum = 3;
3437     HasRC = true;
3438     break;
3439   case X86::BI__builtin_ia32_addss_round_mask:
3440   case X86::BI__builtin_ia32_addsd_round_mask:
3441   case X86::BI__builtin_ia32_divss_round_mask:
3442   case X86::BI__builtin_ia32_divsd_round_mask:
3443   case X86::BI__builtin_ia32_mulss_round_mask:
3444   case X86::BI__builtin_ia32_mulsd_round_mask:
3445   case X86::BI__builtin_ia32_subss_round_mask:
3446   case X86::BI__builtin_ia32_subsd_round_mask:
3447   case X86::BI__builtin_ia32_scalefpd512_mask:
3448   case X86::BI__builtin_ia32_scalefps512_mask:
3449   case X86::BI__builtin_ia32_scalefsd_round_mask:
3450   case X86::BI__builtin_ia32_scalefss_round_mask:
3451   case X86::BI__builtin_ia32_getmantpd512_mask:
3452   case X86::BI__builtin_ia32_getmantps512_mask:
3453   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3454   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3455   case X86::BI__builtin_ia32_sqrtss_round_mask:
3456   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3457   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3458   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3459   case X86::BI__builtin_ia32_vfmaddss3_mask:
3460   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3461   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3462   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3463   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3464   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3465   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3466   case X86::BI__builtin_ia32_vfmaddps512_mask:
3467   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3468   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3469   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3470   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3471   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3472   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3473   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3474   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3475   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3476   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3477   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3478     ArgNum = 4;
3479     HasRC = true;
3480     break;
3481   case X86::BI__builtin_ia32_getmantsd_round_mask:
3482   case X86::BI__builtin_ia32_getmantss_round_mask:
3483     ArgNum = 5;
3484     HasRC = true;
3485     break;
3486   }
3487 
3488   llvm::APSInt Result;
3489 
3490   // We can't check the value of a dependent argument.
3491   Expr *Arg = TheCall->getArg(ArgNum);
3492   if (Arg->isTypeDependent() || Arg->isValueDependent())
3493     return false;
3494 
3495   // Check constant-ness first.
3496   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3497     return true;
3498 
3499   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3500   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3501   // combined with ROUND_NO_EXC.
3502   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3503       Result == 8/*ROUND_NO_EXC*/ ||
3504       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3505     return false;
3506 
3507   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3508          << Arg->getSourceRange();
3509 }
3510 
3511 // Check if the gather/scatter scale is legal.
3512 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3513                                              CallExpr *TheCall) {
3514   unsigned ArgNum = 0;
3515   switch (BuiltinID) {
3516   default:
3517     return false;
3518   case X86::BI__builtin_ia32_gatherpfdpd:
3519   case X86::BI__builtin_ia32_gatherpfdps:
3520   case X86::BI__builtin_ia32_gatherpfqpd:
3521   case X86::BI__builtin_ia32_gatherpfqps:
3522   case X86::BI__builtin_ia32_scatterpfdpd:
3523   case X86::BI__builtin_ia32_scatterpfdps:
3524   case X86::BI__builtin_ia32_scatterpfqpd:
3525   case X86::BI__builtin_ia32_scatterpfqps:
3526     ArgNum = 3;
3527     break;
3528   case X86::BI__builtin_ia32_gatherd_pd:
3529   case X86::BI__builtin_ia32_gatherd_pd256:
3530   case X86::BI__builtin_ia32_gatherq_pd:
3531   case X86::BI__builtin_ia32_gatherq_pd256:
3532   case X86::BI__builtin_ia32_gatherd_ps:
3533   case X86::BI__builtin_ia32_gatherd_ps256:
3534   case X86::BI__builtin_ia32_gatherq_ps:
3535   case X86::BI__builtin_ia32_gatherq_ps256:
3536   case X86::BI__builtin_ia32_gatherd_q:
3537   case X86::BI__builtin_ia32_gatherd_q256:
3538   case X86::BI__builtin_ia32_gatherq_q:
3539   case X86::BI__builtin_ia32_gatherq_q256:
3540   case X86::BI__builtin_ia32_gatherd_d:
3541   case X86::BI__builtin_ia32_gatherd_d256:
3542   case X86::BI__builtin_ia32_gatherq_d:
3543   case X86::BI__builtin_ia32_gatherq_d256:
3544   case X86::BI__builtin_ia32_gather3div2df:
3545   case X86::BI__builtin_ia32_gather3div2di:
3546   case X86::BI__builtin_ia32_gather3div4df:
3547   case X86::BI__builtin_ia32_gather3div4di:
3548   case X86::BI__builtin_ia32_gather3div4sf:
3549   case X86::BI__builtin_ia32_gather3div4si:
3550   case X86::BI__builtin_ia32_gather3div8sf:
3551   case X86::BI__builtin_ia32_gather3div8si:
3552   case X86::BI__builtin_ia32_gather3siv2df:
3553   case X86::BI__builtin_ia32_gather3siv2di:
3554   case X86::BI__builtin_ia32_gather3siv4df:
3555   case X86::BI__builtin_ia32_gather3siv4di:
3556   case X86::BI__builtin_ia32_gather3siv4sf:
3557   case X86::BI__builtin_ia32_gather3siv4si:
3558   case X86::BI__builtin_ia32_gather3siv8sf:
3559   case X86::BI__builtin_ia32_gather3siv8si:
3560   case X86::BI__builtin_ia32_gathersiv8df:
3561   case X86::BI__builtin_ia32_gathersiv16sf:
3562   case X86::BI__builtin_ia32_gatherdiv8df:
3563   case X86::BI__builtin_ia32_gatherdiv16sf:
3564   case X86::BI__builtin_ia32_gathersiv8di:
3565   case X86::BI__builtin_ia32_gathersiv16si:
3566   case X86::BI__builtin_ia32_gatherdiv8di:
3567   case X86::BI__builtin_ia32_gatherdiv16si:
3568   case X86::BI__builtin_ia32_scatterdiv2df:
3569   case X86::BI__builtin_ia32_scatterdiv2di:
3570   case X86::BI__builtin_ia32_scatterdiv4df:
3571   case X86::BI__builtin_ia32_scatterdiv4di:
3572   case X86::BI__builtin_ia32_scatterdiv4sf:
3573   case X86::BI__builtin_ia32_scatterdiv4si:
3574   case X86::BI__builtin_ia32_scatterdiv8sf:
3575   case X86::BI__builtin_ia32_scatterdiv8si:
3576   case X86::BI__builtin_ia32_scattersiv2df:
3577   case X86::BI__builtin_ia32_scattersiv2di:
3578   case X86::BI__builtin_ia32_scattersiv4df:
3579   case X86::BI__builtin_ia32_scattersiv4di:
3580   case X86::BI__builtin_ia32_scattersiv4sf:
3581   case X86::BI__builtin_ia32_scattersiv4si:
3582   case X86::BI__builtin_ia32_scattersiv8sf:
3583   case X86::BI__builtin_ia32_scattersiv8si:
3584   case X86::BI__builtin_ia32_scattersiv8df:
3585   case X86::BI__builtin_ia32_scattersiv16sf:
3586   case X86::BI__builtin_ia32_scatterdiv8df:
3587   case X86::BI__builtin_ia32_scatterdiv16sf:
3588   case X86::BI__builtin_ia32_scattersiv8di:
3589   case X86::BI__builtin_ia32_scattersiv16si:
3590   case X86::BI__builtin_ia32_scatterdiv8di:
3591   case X86::BI__builtin_ia32_scatterdiv16si:
3592     ArgNum = 4;
3593     break;
3594   }
3595 
3596   llvm::APSInt Result;
3597 
3598   // We can't check the value of a dependent argument.
3599   Expr *Arg = TheCall->getArg(ArgNum);
3600   if (Arg->isTypeDependent() || Arg->isValueDependent())
3601     return false;
3602 
3603   // Check constant-ness first.
3604   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3605     return true;
3606 
3607   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3608     return false;
3609 
3610   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3611          << Arg->getSourceRange();
3612 }
3613 
3614 static bool isX86_32Builtin(unsigned BuiltinID) {
3615   // These builtins only work on x86-32 targets.
3616   switch (BuiltinID) {
3617   case X86::BI__builtin_ia32_readeflags_u32:
3618   case X86::BI__builtin_ia32_writeeflags_u32:
3619     return true;
3620   }
3621 
3622   return false;
3623 }
3624 
3625 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
3626   if (BuiltinID == X86::BI__builtin_cpu_supports)
3627     return SemaBuiltinCpuSupports(*this, TheCall);
3628 
3629   if (BuiltinID == X86::BI__builtin_cpu_is)
3630     return SemaBuiltinCpuIs(*this, TheCall);
3631 
3632   // Check for 32-bit only builtins on a 64-bit target.
3633   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
3634   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3635     return Diag(TheCall->getCallee()->getBeginLoc(),
3636                 diag::err_32_bit_builtin_64_bit_tgt);
3637 
3638   // If the intrinsic has rounding or SAE make sure its valid.
3639   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3640     return true;
3641 
3642   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3643   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3644     return true;
3645 
3646   // For intrinsics which take an immediate value as part of the instruction,
3647   // range check them here.
3648   int i = 0, l = 0, u = 0;
3649   switch (BuiltinID) {
3650   default:
3651     return false;
3652   case X86::BI__builtin_ia32_vec_ext_v2si:
3653   case X86::BI__builtin_ia32_vec_ext_v2di:
3654   case X86::BI__builtin_ia32_vextractf128_pd256:
3655   case X86::BI__builtin_ia32_vextractf128_ps256:
3656   case X86::BI__builtin_ia32_vextractf128_si256:
3657   case X86::BI__builtin_ia32_extract128i256:
3658   case X86::BI__builtin_ia32_extractf64x4_mask:
3659   case X86::BI__builtin_ia32_extracti64x4_mask:
3660   case X86::BI__builtin_ia32_extractf32x8_mask:
3661   case X86::BI__builtin_ia32_extracti32x8_mask:
3662   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3663   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3664   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3665   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3666     i = 1; l = 0; u = 1;
3667     break;
3668   case X86::BI__builtin_ia32_vec_set_v2di:
3669   case X86::BI__builtin_ia32_vinsertf128_pd256:
3670   case X86::BI__builtin_ia32_vinsertf128_ps256:
3671   case X86::BI__builtin_ia32_vinsertf128_si256:
3672   case X86::BI__builtin_ia32_insert128i256:
3673   case X86::BI__builtin_ia32_insertf32x8:
3674   case X86::BI__builtin_ia32_inserti32x8:
3675   case X86::BI__builtin_ia32_insertf64x4:
3676   case X86::BI__builtin_ia32_inserti64x4:
3677   case X86::BI__builtin_ia32_insertf64x2_256:
3678   case X86::BI__builtin_ia32_inserti64x2_256:
3679   case X86::BI__builtin_ia32_insertf32x4_256:
3680   case X86::BI__builtin_ia32_inserti32x4_256:
3681     i = 2; l = 0; u = 1;
3682     break;
3683   case X86::BI__builtin_ia32_vpermilpd:
3684   case X86::BI__builtin_ia32_vec_ext_v4hi:
3685   case X86::BI__builtin_ia32_vec_ext_v4si:
3686   case X86::BI__builtin_ia32_vec_ext_v4sf:
3687   case X86::BI__builtin_ia32_vec_ext_v4di:
3688   case X86::BI__builtin_ia32_extractf32x4_mask:
3689   case X86::BI__builtin_ia32_extracti32x4_mask:
3690   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3691   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3692     i = 1; l = 0; u = 3;
3693     break;
3694   case X86::BI_mm_prefetch:
3695   case X86::BI__builtin_ia32_vec_ext_v8hi:
3696   case X86::BI__builtin_ia32_vec_ext_v8si:
3697     i = 1; l = 0; u = 7;
3698     break;
3699   case X86::BI__builtin_ia32_sha1rnds4:
3700   case X86::BI__builtin_ia32_blendpd:
3701   case X86::BI__builtin_ia32_shufpd:
3702   case X86::BI__builtin_ia32_vec_set_v4hi:
3703   case X86::BI__builtin_ia32_vec_set_v4si:
3704   case X86::BI__builtin_ia32_vec_set_v4di:
3705   case X86::BI__builtin_ia32_shuf_f32x4_256:
3706   case X86::BI__builtin_ia32_shuf_f64x2_256:
3707   case X86::BI__builtin_ia32_shuf_i32x4_256:
3708   case X86::BI__builtin_ia32_shuf_i64x2_256:
3709   case X86::BI__builtin_ia32_insertf64x2_512:
3710   case X86::BI__builtin_ia32_inserti64x2_512:
3711   case X86::BI__builtin_ia32_insertf32x4:
3712   case X86::BI__builtin_ia32_inserti32x4:
3713     i = 2; l = 0; u = 3;
3714     break;
3715   case X86::BI__builtin_ia32_vpermil2pd:
3716   case X86::BI__builtin_ia32_vpermil2pd256:
3717   case X86::BI__builtin_ia32_vpermil2ps:
3718   case X86::BI__builtin_ia32_vpermil2ps256:
3719     i = 3; l = 0; u = 3;
3720     break;
3721   case X86::BI__builtin_ia32_cmpb128_mask:
3722   case X86::BI__builtin_ia32_cmpw128_mask:
3723   case X86::BI__builtin_ia32_cmpd128_mask:
3724   case X86::BI__builtin_ia32_cmpq128_mask:
3725   case X86::BI__builtin_ia32_cmpb256_mask:
3726   case X86::BI__builtin_ia32_cmpw256_mask:
3727   case X86::BI__builtin_ia32_cmpd256_mask:
3728   case X86::BI__builtin_ia32_cmpq256_mask:
3729   case X86::BI__builtin_ia32_cmpb512_mask:
3730   case X86::BI__builtin_ia32_cmpw512_mask:
3731   case X86::BI__builtin_ia32_cmpd512_mask:
3732   case X86::BI__builtin_ia32_cmpq512_mask:
3733   case X86::BI__builtin_ia32_ucmpb128_mask:
3734   case X86::BI__builtin_ia32_ucmpw128_mask:
3735   case X86::BI__builtin_ia32_ucmpd128_mask:
3736   case X86::BI__builtin_ia32_ucmpq128_mask:
3737   case X86::BI__builtin_ia32_ucmpb256_mask:
3738   case X86::BI__builtin_ia32_ucmpw256_mask:
3739   case X86::BI__builtin_ia32_ucmpd256_mask:
3740   case X86::BI__builtin_ia32_ucmpq256_mask:
3741   case X86::BI__builtin_ia32_ucmpb512_mask:
3742   case X86::BI__builtin_ia32_ucmpw512_mask:
3743   case X86::BI__builtin_ia32_ucmpd512_mask:
3744   case X86::BI__builtin_ia32_ucmpq512_mask:
3745   case X86::BI__builtin_ia32_vpcomub:
3746   case X86::BI__builtin_ia32_vpcomuw:
3747   case X86::BI__builtin_ia32_vpcomud:
3748   case X86::BI__builtin_ia32_vpcomuq:
3749   case X86::BI__builtin_ia32_vpcomb:
3750   case X86::BI__builtin_ia32_vpcomw:
3751   case X86::BI__builtin_ia32_vpcomd:
3752   case X86::BI__builtin_ia32_vpcomq:
3753   case X86::BI__builtin_ia32_vec_set_v8hi:
3754   case X86::BI__builtin_ia32_vec_set_v8si:
3755     i = 2; l = 0; u = 7;
3756     break;
3757   case X86::BI__builtin_ia32_vpermilpd256:
3758   case X86::BI__builtin_ia32_roundps:
3759   case X86::BI__builtin_ia32_roundpd:
3760   case X86::BI__builtin_ia32_roundps256:
3761   case X86::BI__builtin_ia32_roundpd256:
3762   case X86::BI__builtin_ia32_getmantpd128_mask:
3763   case X86::BI__builtin_ia32_getmantpd256_mask:
3764   case X86::BI__builtin_ia32_getmantps128_mask:
3765   case X86::BI__builtin_ia32_getmantps256_mask:
3766   case X86::BI__builtin_ia32_getmantpd512_mask:
3767   case X86::BI__builtin_ia32_getmantps512_mask:
3768   case X86::BI__builtin_ia32_vec_ext_v16qi:
3769   case X86::BI__builtin_ia32_vec_ext_v16hi:
3770     i = 1; l = 0; u = 15;
3771     break;
3772   case X86::BI__builtin_ia32_pblendd128:
3773   case X86::BI__builtin_ia32_blendps:
3774   case X86::BI__builtin_ia32_blendpd256:
3775   case X86::BI__builtin_ia32_shufpd256:
3776   case X86::BI__builtin_ia32_roundss:
3777   case X86::BI__builtin_ia32_roundsd:
3778   case X86::BI__builtin_ia32_rangepd128_mask:
3779   case X86::BI__builtin_ia32_rangepd256_mask:
3780   case X86::BI__builtin_ia32_rangepd512_mask:
3781   case X86::BI__builtin_ia32_rangeps128_mask:
3782   case X86::BI__builtin_ia32_rangeps256_mask:
3783   case X86::BI__builtin_ia32_rangeps512_mask:
3784   case X86::BI__builtin_ia32_getmantsd_round_mask:
3785   case X86::BI__builtin_ia32_getmantss_round_mask:
3786   case X86::BI__builtin_ia32_vec_set_v16qi:
3787   case X86::BI__builtin_ia32_vec_set_v16hi:
3788     i = 2; l = 0; u = 15;
3789     break;
3790   case X86::BI__builtin_ia32_vec_ext_v32qi:
3791     i = 1; l = 0; u = 31;
3792     break;
3793   case X86::BI__builtin_ia32_cmpps:
3794   case X86::BI__builtin_ia32_cmpss:
3795   case X86::BI__builtin_ia32_cmppd:
3796   case X86::BI__builtin_ia32_cmpsd:
3797   case X86::BI__builtin_ia32_cmpps256:
3798   case X86::BI__builtin_ia32_cmppd256:
3799   case X86::BI__builtin_ia32_cmpps128_mask:
3800   case X86::BI__builtin_ia32_cmppd128_mask:
3801   case X86::BI__builtin_ia32_cmpps256_mask:
3802   case X86::BI__builtin_ia32_cmppd256_mask:
3803   case X86::BI__builtin_ia32_cmpps512_mask:
3804   case X86::BI__builtin_ia32_cmppd512_mask:
3805   case X86::BI__builtin_ia32_cmpsd_mask:
3806   case X86::BI__builtin_ia32_cmpss_mask:
3807   case X86::BI__builtin_ia32_vec_set_v32qi:
3808     i = 2; l = 0; u = 31;
3809     break;
3810   case X86::BI__builtin_ia32_permdf256:
3811   case X86::BI__builtin_ia32_permdi256:
3812   case X86::BI__builtin_ia32_permdf512:
3813   case X86::BI__builtin_ia32_permdi512:
3814   case X86::BI__builtin_ia32_vpermilps:
3815   case X86::BI__builtin_ia32_vpermilps256:
3816   case X86::BI__builtin_ia32_vpermilpd512:
3817   case X86::BI__builtin_ia32_vpermilps512:
3818   case X86::BI__builtin_ia32_pshufd:
3819   case X86::BI__builtin_ia32_pshufd256:
3820   case X86::BI__builtin_ia32_pshufd512:
3821   case X86::BI__builtin_ia32_pshufhw:
3822   case X86::BI__builtin_ia32_pshufhw256:
3823   case X86::BI__builtin_ia32_pshufhw512:
3824   case X86::BI__builtin_ia32_pshuflw:
3825   case X86::BI__builtin_ia32_pshuflw256:
3826   case X86::BI__builtin_ia32_pshuflw512:
3827   case X86::BI__builtin_ia32_vcvtps2ph:
3828   case X86::BI__builtin_ia32_vcvtps2ph_mask:
3829   case X86::BI__builtin_ia32_vcvtps2ph256:
3830   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
3831   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
3832   case X86::BI__builtin_ia32_rndscaleps_128_mask:
3833   case X86::BI__builtin_ia32_rndscalepd_128_mask:
3834   case X86::BI__builtin_ia32_rndscaleps_256_mask:
3835   case X86::BI__builtin_ia32_rndscalepd_256_mask:
3836   case X86::BI__builtin_ia32_rndscaleps_mask:
3837   case X86::BI__builtin_ia32_rndscalepd_mask:
3838   case X86::BI__builtin_ia32_reducepd128_mask:
3839   case X86::BI__builtin_ia32_reducepd256_mask:
3840   case X86::BI__builtin_ia32_reducepd512_mask:
3841   case X86::BI__builtin_ia32_reduceps128_mask:
3842   case X86::BI__builtin_ia32_reduceps256_mask:
3843   case X86::BI__builtin_ia32_reduceps512_mask:
3844   case X86::BI__builtin_ia32_prold512:
3845   case X86::BI__builtin_ia32_prolq512:
3846   case X86::BI__builtin_ia32_prold128:
3847   case X86::BI__builtin_ia32_prold256:
3848   case X86::BI__builtin_ia32_prolq128:
3849   case X86::BI__builtin_ia32_prolq256:
3850   case X86::BI__builtin_ia32_prord512:
3851   case X86::BI__builtin_ia32_prorq512:
3852   case X86::BI__builtin_ia32_prord128:
3853   case X86::BI__builtin_ia32_prord256:
3854   case X86::BI__builtin_ia32_prorq128:
3855   case X86::BI__builtin_ia32_prorq256:
3856   case X86::BI__builtin_ia32_fpclasspd128_mask:
3857   case X86::BI__builtin_ia32_fpclasspd256_mask:
3858   case X86::BI__builtin_ia32_fpclassps128_mask:
3859   case X86::BI__builtin_ia32_fpclassps256_mask:
3860   case X86::BI__builtin_ia32_fpclassps512_mask:
3861   case X86::BI__builtin_ia32_fpclasspd512_mask:
3862   case X86::BI__builtin_ia32_fpclasssd_mask:
3863   case X86::BI__builtin_ia32_fpclassss_mask:
3864   case X86::BI__builtin_ia32_pslldqi128_byteshift:
3865   case X86::BI__builtin_ia32_pslldqi256_byteshift:
3866   case X86::BI__builtin_ia32_pslldqi512_byteshift:
3867   case X86::BI__builtin_ia32_psrldqi128_byteshift:
3868   case X86::BI__builtin_ia32_psrldqi256_byteshift:
3869   case X86::BI__builtin_ia32_psrldqi512_byteshift:
3870   case X86::BI__builtin_ia32_kshiftliqi:
3871   case X86::BI__builtin_ia32_kshiftlihi:
3872   case X86::BI__builtin_ia32_kshiftlisi:
3873   case X86::BI__builtin_ia32_kshiftlidi:
3874   case X86::BI__builtin_ia32_kshiftriqi:
3875   case X86::BI__builtin_ia32_kshiftrihi:
3876   case X86::BI__builtin_ia32_kshiftrisi:
3877   case X86::BI__builtin_ia32_kshiftridi:
3878     i = 1; l = 0; u = 255;
3879     break;
3880   case X86::BI__builtin_ia32_vperm2f128_pd256:
3881   case X86::BI__builtin_ia32_vperm2f128_ps256:
3882   case X86::BI__builtin_ia32_vperm2f128_si256:
3883   case X86::BI__builtin_ia32_permti256:
3884   case X86::BI__builtin_ia32_pblendw128:
3885   case X86::BI__builtin_ia32_pblendw256:
3886   case X86::BI__builtin_ia32_blendps256:
3887   case X86::BI__builtin_ia32_pblendd256:
3888   case X86::BI__builtin_ia32_palignr128:
3889   case X86::BI__builtin_ia32_palignr256:
3890   case X86::BI__builtin_ia32_palignr512:
3891   case X86::BI__builtin_ia32_alignq512:
3892   case X86::BI__builtin_ia32_alignd512:
3893   case X86::BI__builtin_ia32_alignd128:
3894   case X86::BI__builtin_ia32_alignd256:
3895   case X86::BI__builtin_ia32_alignq128:
3896   case X86::BI__builtin_ia32_alignq256:
3897   case X86::BI__builtin_ia32_vcomisd:
3898   case X86::BI__builtin_ia32_vcomiss:
3899   case X86::BI__builtin_ia32_shuf_f32x4:
3900   case X86::BI__builtin_ia32_shuf_f64x2:
3901   case X86::BI__builtin_ia32_shuf_i32x4:
3902   case X86::BI__builtin_ia32_shuf_i64x2:
3903   case X86::BI__builtin_ia32_shufpd512:
3904   case X86::BI__builtin_ia32_shufps:
3905   case X86::BI__builtin_ia32_shufps256:
3906   case X86::BI__builtin_ia32_shufps512:
3907   case X86::BI__builtin_ia32_dbpsadbw128:
3908   case X86::BI__builtin_ia32_dbpsadbw256:
3909   case X86::BI__builtin_ia32_dbpsadbw512:
3910   case X86::BI__builtin_ia32_vpshldd128:
3911   case X86::BI__builtin_ia32_vpshldd256:
3912   case X86::BI__builtin_ia32_vpshldd512:
3913   case X86::BI__builtin_ia32_vpshldq128:
3914   case X86::BI__builtin_ia32_vpshldq256:
3915   case X86::BI__builtin_ia32_vpshldq512:
3916   case X86::BI__builtin_ia32_vpshldw128:
3917   case X86::BI__builtin_ia32_vpshldw256:
3918   case X86::BI__builtin_ia32_vpshldw512:
3919   case X86::BI__builtin_ia32_vpshrdd128:
3920   case X86::BI__builtin_ia32_vpshrdd256:
3921   case X86::BI__builtin_ia32_vpshrdd512:
3922   case X86::BI__builtin_ia32_vpshrdq128:
3923   case X86::BI__builtin_ia32_vpshrdq256:
3924   case X86::BI__builtin_ia32_vpshrdq512:
3925   case X86::BI__builtin_ia32_vpshrdw128:
3926   case X86::BI__builtin_ia32_vpshrdw256:
3927   case X86::BI__builtin_ia32_vpshrdw512:
3928     i = 2; l = 0; u = 255;
3929     break;
3930   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3931   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3932   case X86::BI__builtin_ia32_fixupimmps512_mask:
3933   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3934   case X86::BI__builtin_ia32_fixupimmsd_mask:
3935   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3936   case X86::BI__builtin_ia32_fixupimmss_mask:
3937   case X86::BI__builtin_ia32_fixupimmss_maskz:
3938   case X86::BI__builtin_ia32_fixupimmpd128_mask:
3939   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
3940   case X86::BI__builtin_ia32_fixupimmpd256_mask:
3941   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
3942   case X86::BI__builtin_ia32_fixupimmps128_mask:
3943   case X86::BI__builtin_ia32_fixupimmps128_maskz:
3944   case X86::BI__builtin_ia32_fixupimmps256_mask:
3945   case X86::BI__builtin_ia32_fixupimmps256_maskz:
3946   case X86::BI__builtin_ia32_pternlogd512_mask:
3947   case X86::BI__builtin_ia32_pternlogd512_maskz:
3948   case X86::BI__builtin_ia32_pternlogq512_mask:
3949   case X86::BI__builtin_ia32_pternlogq512_maskz:
3950   case X86::BI__builtin_ia32_pternlogd128_mask:
3951   case X86::BI__builtin_ia32_pternlogd128_maskz:
3952   case X86::BI__builtin_ia32_pternlogd256_mask:
3953   case X86::BI__builtin_ia32_pternlogd256_maskz:
3954   case X86::BI__builtin_ia32_pternlogq128_mask:
3955   case X86::BI__builtin_ia32_pternlogq128_maskz:
3956   case X86::BI__builtin_ia32_pternlogq256_mask:
3957   case X86::BI__builtin_ia32_pternlogq256_maskz:
3958     i = 3; l = 0; u = 255;
3959     break;
3960   case X86::BI__builtin_ia32_gatherpfdpd:
3961   case X86::BI__builtin_ia32_gatherpfdps:
3962   case X86::BI__builtin_ia32_gatherpfqpd:
3963   case X86::BI__builtin_ia32_gatherpfqps:
3964   case X86::BI__builtin_ia32_scatterpfdpd:
3965   case X86::BI__builtin_ia32_scatterpfdps:
3966   case X86::BI__builtin_ia32_scatterpfqpd:
3967   case X86::BI__builtin_ia32_scatterpfqps:
3968     i = 4; l = 2; u = 3;
3969     break;
3970   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3971   case X86::BI__builtin_ia32_rndscaless_round_mask:
3972     i = 4; l = 0; u = 255;
3973     break;
3974   }
3975 
3976   // Note that we don't force a hard error on the range check here, allowing
3977   // template-generated or macro-generated dead code to potentially have out-of-
3978   // range values. These need to code generate, but don't need to necessarily
3979   // make any sense. We use a warning that defaults to an error.
3980   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
3981 }
3982 
3983 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
3984 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
3985 /// Returns true when the format fits the function and the FormatStringInfo has
3986 /// been populated.
3987 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
3988                                FormatStringInfo *FSI) {
3989   FSI->HasVAListArg = Format->getFirstArg() == 0;
3990   FSI->FormatIdx = Format->getFormatIdx() - 1;
3991   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
3992 
3993   // The way the format attribute works in GCC, the implicit this argument
3994   // of member functions is counted. However, it doesn't appear in our own
3995   // lists, so decrement format_idx in that case.
3996   if (IsCXXMember) {
3997     if(FSI->FormatIdx == 0)
3998       return false;
3999     --FSI->FormatIdx;
4000     if (FSI->FirstDataArg != 0)
4001       --FSI->FirstDataArg;
4002   }
4003   return true;
4004 }
4005 
4006 /// Checks if a the given expression evaluates to null.
4007 ///
4008 /// Returns true if the value evaluates to null.
4009 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4010   // If the expression has non-null type, it doesn't evaluate to null.
4011   if (auto nullability
4012         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4013     if (*nullability == NullabilityKind::NonNull)
4014       return false;
4015   }
4016 
4017   // As a special case, transparent unions initialized with zero are
4018   // considered null for the purposes of the nonnull attribute.
4019   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4020     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4021       if (const CompoundLiteralExpr *CLE =
4022           dyn_cast<CompoundLiteralExpr>(Expr))
4023         if (const InitListExpr *ILE =
4024             dyn_cast<InitListExpr>(CLE->getInitializer()))
4025           Expr = ILE->getInit(0);
4026   }
4027 
4028   bool Result;
4029   return (!Expr->isValueDependent() &&
4030           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4031           !Result);
4032 }
4033 
4034 static void CheckNonNullArgument(Sema &S,
4035                                  const Expr *ArgExpr,
4036                                  SourceLocation CallSiteLoc) {
4037   if (CheckNonNullExpr(S, ArgExpr))
4038     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4039            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
4040 }
4041 
4042 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4043   FormatStringInfo FSI;
4044   if ((GetFormatStringType(Format) == FST_NSString) &&
4045       getFormatStringInfo(Format, false, &FSI)) {
4046     Idx = FSI.FormatIdx;
4047     return true;
4048   }
4049   return false;
4050 }
4051 
4052 /// Diagnose use of %s directive in an NSString which is being passed
4053 /// as formatting string to formatting method.
4054 static void
4055 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4056                                         const NamedDecl *FDecl,
4057                                         Expr **Args,
4058                                         unsigned NumArgs) {
4059   unsigned Idx = 0;
4060   bool Format = false;
4061   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4062   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4063     Idx = 2;
4064     Format = true;
4065   }
4066   else
4067     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4068       if (S.GetFormatNSStringIdx(I, Idx)) {
4069         Format = true;
4070         break;
4071       }
4072     }
4073   if (!Format || NumArgs <= Idx)
4074     return;
4075   const Expr *FormatExpr = Args[Idx];
4076   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4077     FormatExpr = CSCE->getSubExpr();
4078   const StringLiteral *FormatString;
4079   if (const ObjCStringLiteral *OSL =
4080       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4081     FormatString = OSL->getString();
4082   else
4083     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4084   if (!FormatString)
4085     return;
4086   if (S.FormatStringHasSArg(FormatString)) {
4087     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4088       << "%s" << 1 << 1;
4089     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4090       << FDecl->getDeclName();
4091   }
4092 }
4093 
4094 /// Determine whether the given type has a non-null nullability annotation.
4095 static bool isNonNullType(ASTContext &ctx, QualType type) {
4096   if (auto nullability = type->getNullability(ctx))
4097     return *nullability == NullabilityKind::NonNull;
4098 
4099   return false;
4100 }
4101 
4102 static void CheckNonNullArguments(Sema &S,
4103                                   const NamedDecl *FDecl,
4104                                   const FunctionProtoType *Proto,
4105                                   ArrayRef<const Expr *> Args,
4106                                   SourceLocation CallSiteLoc) {
4107   assert((FDecl || Proto) && "Need a function declaration or prototype");
4108 
4109   // Check the attributes attached to the method/function itself.
4110   llvm::SmallBitVector NonNullArgs;
4111   if (FDecl) {
4112     // Handle the nonnull attribute on the function/method declaration itself.
4113     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4114       if (!NonNull->args_size()) {
4115         // Easy case: all pointer arguments are nonnull.
4116         for (const auto *Arg : Args)
4117           if (S.isValidPointerAttrType(Arg->getType()))
4118             CheckNonNullArgument(S, Arg, CallSiteLoc);
4119         return;
4120       }
4121 
4122       for (const ParamIdx &Idx : NonNull->args()) {
4123         unsigned IdxAST = Idx.getASTIndex();
4124         if (IdxAST >= Args.size())
4125           continue;
4126         if (NonNullArgs.empty())
4127           NonNullArgs.resize(Args.size());
4128         NonNullArgs.set(IdxAST);
4129       }
4130     }
4131   }
4132 
4133   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4134     // Handle the nonnull attribute on the parameters of the
4135     // function/method.
4136     ArrayRef<ParmVarDecl*> parms;
4137     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4138       parms = FD->parameters();
4139     else
4140       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4141 
4142     unsigned ParamIndex = 0;
4143     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4144          I != E; ++I, ++ParamIndex) {
4145       const ParmVarDecl *PVD = *I;
4146       if (PVD->hasAttr<NonNullAttr>() ||
4147           isNonNullType(S.Context, PVD->getType())) {
4148         if (NonNullArgs.empty())
4149           NonNullArgs.resize(Args.size());
4150 
4151         NonNullArgs.set(ParamIndex);
4152       }
4153     }
4154   } else {
4155     // If we have a non-function, non-method declaration but no
4156     // function prototype, try to dig out the function prototype.
4157     if (!Proto) {
4158       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4159         QualType type = VD->getType().getNonReferenceType();
4160         if (auto pointerType = type->getAs<PointerType>())
4161           type = pointerType->getPointeeType();
4162         else if (auto blockType = type->getAs<BlockPointerType>())
4163           type = blockType->getPointeeType();
4164         // FIXME: data member pointers?
4165 
4166         // Dig out the function prototype, if there is one.
4167         Proto = type->getAs<FunctionProtoType>();
4168       }
4169     }
4170 
4171     // Fill in non-null argument information from the nullability
4172     // information on the parameter types (if we have them).
4173     if (Proto) {
4174       unsigned Index = 0;
4175       for (auto paramType : Proto->getParamTypes()) {
4176         if (isNonNullType(S.Context, paramType)) {
4177           if (NonNullArgs.empty())
4178             NonNullArgs.resize(Args.size());
4179 
4180           NonNullArgs.set(Index);
4181         }
4182 
4183         ++Index;
4184       }
4185     }
4186   }
4187 
4188   // Check for non-null arguments.
4189   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4190        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4191     if (NonNullArgs[ArgIndex])
4192       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4193   }
4194 }
4195 
4196 /// Handles the checks for format strings, non-POD arguments to vararg
4197 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4198 /// attributes.
4199 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4200                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4201                      bool IsMemberFunction, SourceLocation Loc,
4202                      SourceRange Range, VariadicCallType CallType) {
4203   // FIXME: We should check as much as we can in the template definition.
4204   if (CurContext->isDependentContext())
4205     return;
4206 
4207   // Printf and scanf checking.
4208   llvm::SmallBitVector CheckedVarArgs;
4209   if (FDecl) {
4210     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4211       // Only create vector if there are format attributes.
4212       CheckedVarArgs.resize(Args.size());
4213 
4214       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4215                            CheckedVarArgs);
4216     }
4217   }
4218 
4219   // Refuse POD arguments that weren't caught by the format string
4220   // checks above.
4221   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4222   if (CallType != VariadicDoesNotApply &&
4223       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4224     unsigned NumParams = Proto ? Proto->getNumParams()
4225                        : FDecl && isa<FunctionDecl>(FDecl)
4226                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4227                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4228                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4229                        : 0;
4230 
4231     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4232       // Args[ArgIdx] can be null in malformed code.
4233       if (const Expr *Arg = Args[ArgIdx]) {
4234         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4235           checkVariadicArgument(Arg, CallType);
4236       }
4237     }
4238   }
4239 
4240   if (FDecl || Proto) {
4241     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4242 
4243     // Type safety checking.
4244     if (FDecl) {
4245       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4246         CheckArgumentWithTypeTag(I, Args, Loc);
4247     }
4248   }
4249 
4250   if (FD)
4251     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4252 }
4253 
4254 /// CheckConstructorCall - Check a constructor call for correctness and safety
4255 /// properties not enforced by the C type system.
4256 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4257                                 ArrayRef<const Expr *> Args,
4258                                 const FunctionProtoType *Proto,
4259                                 SourceLocation Loc) {
4260   VariadicCallType CallType =
4261     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4262   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4263             Loc, SourceRange(), CallType);
4264 }
4265 
4266 /// CheckFunctionCall - Check a direct function call for various correctness
4267 /// and safety properties not strictly enforced by the C type system.
4268 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4269                              const FunctionProtoType *Proto) {
4270   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4271                               isa<CXXMethodDecl>(FDecl);
4272   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4273                           IsMemberOperatorCall;
4274   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4275                                                   TheCall->getCallee());
4276   Expr** Args = TheCall->getArgs();
4277   unsigned NumArgs = TheCall->getNumArgs();
4278 
4279   Expr *ImplicitThis = nullptr;
4280   if (IsMemberOperatorCall) {
4281     // If this is a call to a member operator, hide the first argument
4282     // from checkCall.
4283     // FIXME: Our choice of AST representation here is less than ideal.
4284     ImplicitThis = Args[0];
4285     ++Args;
4286     --NumArgs;
4287   } else if (IsMemberFunction)
4288     ImplicitThis =
4289         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4290 
4291   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4292             IsMemberFunction, TheCall->getRParenLoc(),
4293             TheCall->getCallee()->getSourceRange(), CallType);
4294 
4295   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4296   // None of the checks below are needed for functions that don't have
4297   // simple names (e.g., C++ conversion functions).
4298   if (!FnInfo)
4299     return false;
4300 
4301   CheckAbsoluteValueFunction(TheCall, FDecl);
4302   CheckMaxUnsignedZero(TheCall, FDecl);
4303 
4304   if (getLangOpts().ObjC)
4305     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4306 
4307   unsigned CMId = FDecl->getMemoryFunctionKind();
4308   if (CMId == 0)
4309     return false;
4310 
4311   // Handle memory setting and copying functions.
4312   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
4313     CheckStrlcpycatArguments(TheCall, FnInfo);
4314   else if (CMId == Builtin::BIstrncat)
4315     CheckStrncatArguments(TheCall, FnInfo);
4316   else
4317     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4318 
4319   return false;
4320 }
4321 
4322 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4323                                ArrayRef<const Expr *> Args) {
4324   VariadicCallType CallType =
4325       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4326 
4327   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4328             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4329             CallType);
4330 
4331   return false;
4332 }
4333 
4334 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4335                             const FunctionProtoType *Proto) {
4336   QualType Ty;
4337   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4338     Ty = V->getType().getNonReferenceType();
4339   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4340     Ty = F->getType().getNonReferenceType();
4341   else
4342     return false;
4343 
4344   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4345       !Ty->isFunctionProtoType())
4346     return false;
4347 
4348   VariadicCallType CallType;
4349   if (!Proto || !Proto->isVariadic()) {
4350     CallType = VariadicDoesNotApply;
4351   } else if (Ty->isBlockPointerType()) {
4352     CallType = VariadicBlock;
4353   } else { // Ty->isFunctionPointerType()
4354     CallType = VariadicFunction;
4355   }
4356 
4357   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4358             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4359             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4360             TheCall->getCallee()->getSourceRange(), CallType);
4361 
4362   return false;
4363 }
4364 
4365 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4366 /// such as function pointers returned from functions.
4367 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4368   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4369                                                   TheCall->getCallee());
4370   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4371             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4372             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4373             TheCall->getCallee()->getSourceRange(), CallType);
4374 
4375   return false;
4376 }
4377 
4378 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4379   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4380     return false;
4381 
4382   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4383   switch (Op) {
4384   case AtomicExpr::AO__c11_atomic_init:
4385   case AtomicExpr::AO__opencl_atomic_init:
4386     llvm_unreachable("There is no ordering argument for an init");
4387 
4388   case AtomicExpr::AO__c11_atomic_load:
4389   case AtomicExpr::AO__opencl_atomic_load:
4390   case AtomicExpr::AO__atomic_load_n:
4391   case AtomicExpr::AO__atomic_load:
4392     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4393            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4394 
4395   case AtomicExpr::AO__c11_atomic_store:
4396   case AtomicExpr::AO__opencl_atomic_store:
4397   case AtomicExpr::AO__atomic_store:
4398   case AtomicExpr::AO__atomic_store_n:
4399     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4400            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4401            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4402 
4403   default:
4404     return true;
4405   }
4406 }
4407 
4408 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4409                                          AtomicExpr::AtomicOp Op) {
4410   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4411   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4412 
4413   // All the non-OpenCL operations take one of the following forms.
4414   // The OpenCL operations take the __c11 forms with one extra argument for
4415   // synchronization scope.
4416   enum {
4417     // C    __c11_atomic_init(A *, C)
4418     Init,
4419 
4420     // C    __c11_atomic_load(A *, int)
4421     Load,
4422 
4423     // void __atomic_load(A *, CP, int)
4424     LoadCopy,
4425 
4426     // void __atomic_store(A *, CP, int)
4427     Copy,
4428 
4429     // C    __c11_atomic_add(A *, M, int)
4430     Arithmetic,
4431 
4432     // C    __atomic_exchange_n(A *, CP, int)
4433     Xchg,
4434 
4435     // void __atomic_exchange(A *, C *, CP, int)
4436     GNUXchg,
4437 
4438     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4439     C11CmpXchg,
4440 
4441     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4442     GNUCmpXchg
4443   } Form = Init;
4444 
4445   const unsigned NumForm = GNUCmpXchg + 1;
4446   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4447   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4448   // where:
4449   //   C is an appropriate type,
4450   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4451   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4452   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4453   //   the int parameters are for orderings.
4454 
4455   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4456       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4457       "need to update code for modified forms");
4458   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4459                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
4460                         AtomicExpr::AO__atomic_load,
4461                 "need to update code for modified C11 atomics");
4462   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4463                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4464   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4465                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
4466                IsOpenCL;
4467   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4468              Op == AtomicExpr::AO__atomic_store_n ||
4469              Op == AtomicExpr::AO__atomic_exchange_n ||
4470              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4471   bool IsAddSub = false;
4472   bool IsMinMax = false;
4473 
4474   switch (Op) {
4475   case AtomicExpr::AO__c11_atomic_init:
4476   case AtomicExpr::AO__opencl_atomic_init:
4477     Form = Init;
4478     break;
4479 
4480   case AtomicExpr::AO__c11_atomic_load:
4481   case AtomicExpr::AO__opencl_atomic_load:
4482   case AtomicExpr::AO__atomic_load_n:
4483     Form = Load;
4484     break;
4485 
4486   case AtomicExpr::AO__atomic_load:
4487     Form = LoadCopy;
4488     break;
4489 
4490   case AtomicExpr::AO__c11_atomic_store:
4491   case AtomicExpr::AO__opencl_atomic_store:
4492   case AtomicExpr::AO__atomic_store:
4493   case AtomicExpr::AO__atomic_store_n:
4494     Form = Copy;
4495     break;
4496 
4497   case AtomicExpr::AO__c11_atomic_fetch_add:
4498   case AtomicExpr::AO__c11_atomic_fetch_sub:
4499   case AtomicExpr::AO__opencl_atomic_fetch_add:
4500   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4501   case AtomicExpr::AO__opencl_atomic_fetch_min:
4502   case AtomicExpr::AO__opencl_atomic_fetch_max:
4503   case AtomicExpr::AO__atomic_fetch_add:
4504   case AtomicExpr::AO__atomic_fetch_sub:
4505   case AtomicExpr::AO__atomic_add_fetch:
4506   case AtomicExpr::AO__atomic_sub_fetch:
4507     IsAddSub = true;
4508     LLVM_FALLTHROUGH;
4509   case AtomicExpr::AO__c11_atomic_fetch_and:
4510   case AtomicExpr::AO__c11_atomic_fetch_or:
4511   case AtomicExpr::AO__c11_atomic_fetch_xor:
4512   case AtomicExpr::AO__opencl_atomic_fetch_and:
4513   case AtomicExpr::AO__opencl_atomic_fetch_or:
4514   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4515   case AtomicExpr::AO__atomic_fetch_and:
4516   case AtomicExpr::AO__atomic_fetch_or:
4517   case AtomicExpr::AO__atomic_fetch_xor:
4518   case AtomicExpr::AO__atomic_fetch_nand:
4519   case AtomicExpr::AO__atomic_and_fetch:
4520   case AtomicExpr::AO__atomic_or_fetch:
4521   case AtomicExpr::AO__atomic_xor_fetch:
4522   case AtomicExpr::AO__atomic_nand_fetch:
4523     Form = Arithmetic;
4524     break;
4525 
4526   case AtomicExpr::AO__atomic_fetch_min:
4527   case AtomicExpr::AO__atomic_fetch_max:
4528     IsMinMax = true;
4529     Form = Arithmetic;
4530     break;
4531 
4532   case AtomicExpr::AO__c11_atomic_exchange:
4533   case AtomicExpr::AO__opencl_atomic_exchange:
4534   case AtomicExpr::AO__atomic_exchange_n:
4535     Form = Xchg;
4536     break;
4537 
4538   case AtomicExpr::AO__atomic_exchange:
4539     Form = GNUXchg;
4540     break;
4541 
4542   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4543   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4544   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4545   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4546     Form = C11CmpXchg;
4547     break;
4548 
4549   case AtomicExpr::AO__atomic_compare_exchange:
4550   case AtomicExpr::AO__atomic_compare_exchange_n:
4551     Form = GNUCmpXchg;
4552     break;
4553   }
4554 
4555   unsigned AdjustedNumArgs = NumArgs[Form];
4556   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4557     ++AdjustedNumArgs;
4558   // Check we have the right number of arguments.
4559   if (TheCall->getNumArgs() < AdjustedNumArgs) {
4560     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
4561         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4562         << TheCall->getCallee()->getSourceRange();
4563     return ExprError();
4564   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
4565     Diag(TheCall->getArg(AdjustedNumArgs)->getBeginLoc(),
4566          diag::err_typecheck_call_too_many_args)
4567         << 0 << AdjustedNumArgs << TheCall->getNumArgs()
4568         << TheCall->getCallee()->getSourceRange();
4569     return ExprError();
4570   }
4571 
4572   // Inspect the first argument of the atomic operation.
4573   Expr *Ptr = TheCall->getArg(0);
4574   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4575   if (ConvertedPtr.isInvalid())
4576     return ExprError();
4577 
4578   Ptr = ConvertedPtr.get();
4579   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4580   if (!pointerType) {
4581     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4582         << Ptr->getType() << Ptr->getSourceRange();
4583     return ExprError();
4584   }
4585 
4586   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4587   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4588   QualType ValType = AtomTy; // 'C'
4589   if (IsC11) {
4590     if (!AtomTy->isAtomicType()) {
4591       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic)
4592           << Ptr->getType() << Ptr->getSourceRange();
4593       return ExprError();
4594     }
4595     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4596         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4597       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_atomic)
4598           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4599           << Ptr->getSourceRange();
4600       return ExprError();
4601     }
4602     ValType = AtomTy->getAs<AtomicType>()->getValueType();
4603   } else if (Form != Load && Form != LoadCopy) {
4604     if (ValType.isConstQualified()) {
4605       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_non_const_pointer)
4606           << Ptr->getType() << Ptr->getSourceRange();
4607       return ExprError();
4608     }
4609   }
4610 
4611   // For an arithmetic operation, the implied arithmetic must be well-formed.
4612   if (Form == Arithmetic) {
4613     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4614     if (IsAddSub && !ValType->isIntegerType()
4615         && !ValType->isPointerType()) {
4616       Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4617           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4618       return ExprError();
4619     }
4620     if (IsMinMax) {
4621       const BuiltinType *BT = ValType->getAs<BuiltinType>();
4622       if (!BT || (BT->getKind() != BuiltinType::Int &&
4623                   BT->getKind() != BuiltinType::UInt)) {
4624         Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_int32_or_ptr);
4625         return ExprError();
4626       }
4627     }
4628     if (!IsAddSub && !IsMinMax && !ValType->isIntegerType()) {
4629       Diag(DRE->getBeginLoc(), diag::err_atomic_op_bitwise_needs_atomic_int)
4630           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4631       return ExprError();
4632     }
4633     if (IsC11 && ValType->isPointerType() &&
4634         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4635                             diag::err_incomplete_type)) {
4636       return ExprError();
4637     }
4638   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4639     // For __atomic_*_n operations, the value type must be a scalar integral or
4640     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4641     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4642         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4643     return ExprError();
4644   }
4645 
4646   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4647       !AtomTy->isScalarType()) {
4648     // For GNU atomics, require a trivially-copyable type. This is not part of
4649     // the GNU atomics specification, but we enforce it for sanity.
4650     Diag(DRE->getBeginLoc(), diag::err_atomic_op_needs_trivial_copy)
4651         << Ptr->getType() << Ptr->getSourceRange();
4652     return ExprError();
4653   }
4654 
4655   switch (ValType.getObjCLifetime()) {
4656   case Qualifiers::OCL_None:
4657   case Qualifiers::OCL_ExplicitNone:
4658     // okay
4659     break;
4660 
4661   case Qualifiers::OCL_Weak:
4662   case Qualifiers::OCL_Strong:
4663   case Qualifiers::OCL_Autoreleasing:
4664     // FIXME: Can this happen? By this point, ValType should be known
4665     // to be trivially copyable.
4666     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4667         << ValType << Ptr->getSourceRange();
4668     return ExprError();
4669   }
4670 
4671   // All atomic operations have an overload which takes a pointer to a volatile
4672   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4673   // into the result or the other operands. Similarly atomic_load takes a
4674   // pointer to a const 'A'.
4675   ValType.removeLocalVolatile();
4676   ValType.removeLocalConst();
4677   QualType ResultType = ValType;
4678   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4679       Form == Init)
4680     ResultType = Context.VoidTy;
4681   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4682     ResultType = Context.BoolTy;
4683 
4684   // The type of a parameter passed 'by value'. In the GNU atomics, such
4685   // arguments are actually passed as pointers.
4686   QualType ByValType = ValType; // 'CP'
4687   bool IsPassedByAddress = false;
4688   if (!IsC11 && !IsN) {
4689     ByValType = Ptr->getType();
4690     IsPassedByAddress = true;
4691   }
4692 
4693   // The first argument's non-CV pointer type is used to deduce the type of
4694   // subsequent arguments, except for:
4695   //  - weak flag (always converted to bool)
4696   //  - memory order (always converted to int)
4697   //  - scope  (always converted to int)
4698   for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
4699     QualType Ty;
4700     if (i < NumVals[Form] + 1) {
4701       switch (i) {
4702       case 0:
4703         // The first argument is always a pointer. It has a fixed type.
4704         // It is always dereferenced, a nullptr is undefined.
4705         CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4706         // Nothing else to do: we already know all we want about this pointer.
4707         continue;
4708       case 1:
4709         // The second argument is the non-atomic operand. For arithmetic, this
4710         // is always passed by value, and for a compare_exchange it is always
4711         // passed by address. For the rest, GNU uses by-address and C11 uses
4712         // by-value.
4713         assert(Form != Load);
4714         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
4715           Ty = ValType;
4716         else if (Form == Copy || Form == Xchg) {
4717           if (IsPassedByAddress)
4718             // The value pointer is always dereferenced, a nullptr is undefined.
4719             CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4720           Ty = ByValType;
4721         } else if (Form == Arithmetic)
4722           Ty = Context.getPointerDiffType();
4723         else {
4724           Expr *ValArg = TheCall->getArg(i);
4725           // The value pointer is always dereferenced, a nullptr is undefined.
4726           CheckNonNullArgument(*this, ValArg, DRE->getBeginLoc());
4727           LangAS AS = LangAS::Default;
4728           // Keep address space of non-atomic pointer type.
4729           if (const PointerType *PtrTy =
4730                   ValArg->getType()->getAs<PointerType>()) {
4731             AS = PtrTy->getPointeeType().getAddressSpace();
4732           }
4733           Ty = Context.getPointerType(
4734               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
4735         }
4736         break;
4737       case 2:
4738         // The third argument to compare_exchange / GNU exchange is the desired
4739         // value, either by-value (for the C11 and *_n variant) or as a pointer.
4740         if (IsPassedByAddress)
4741           CheckNonNullArgument(*this, TheCall->getArg(i), DRE->getBeginLoc());
4742         Ty = ByValType;
4743         break;
4744       case 3:
4745         // The fourth argument to GNU compare_exchange is a 'weak' flag.
4746         Ty = Context.BoolTy;
4747         break;
4748       }
4749     } else {
4750       // The order(s) and scope are always converted to int.
4751       Ty = Context.IntTy;
4752     }
4753 
4754     InitializedEntity Entity =
4755         InitializedEntity::InitializeParameter(Context, Ty, false);
4756     ExprResult Arg = TheCall->getArg(i);
4757     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4758     if (Arg.isInvalid())
4759       return true;
4760     TheCall->setArg(i, Arg.get());
4761   }
4762 
4763   // Permute the arguments into a 'consistent' order.
4764   SmallVector<Expr*, 5> SubExprs;
4765   SubExprs.push_back(Ptr);
4766   switch (Form) {
4767   case Init:
4768     // Note, AtomicExpr::getVal1() has a special case for this atomic.
4769     SubExprs.push_back(TheCall->getArg(1)); // Val1
4770     break;
4771   case Load:
4772     SubExprs.push_back(TheCall->getArg(1)); // Order
4773     break;
4774   case LoadCopy:
4775   case Copy:
4776   case Arithmetic:
4777   case Xchg:
4778     SubExprs.push_back(TheCall->getArg(2)); // Order
4779     SubExprs.push_back(TheCall->getArg(1)); // Val1
4780     break;
4781   case GNUXchg:
4782     // Note, AtomicExpr::getVal2() has a special case for this atomic.
4783     SubExprs.push_back(TheCall->getArg(3)); // Order
4784     SubExprs.push_back(TheCall->getArg(1)); // Val1
4785     SubExprs.push_back(TheCall->getArg(2)); // Val2
4786     break;
4787   case C11CmpXchg:
4788     SubExprs.push_back(TheCall->getArg(3)); // Order
4789     SubExprs.push_back(TheCall->getArg(1)); // Val1
4790     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
4791     SubExprs.push_back(TheCall->getArg(2)); // Val2
4792     break;
4793   case GNUCmpXchg:
4794     SubExprs.push_back(TheCall->getArg(4)); // Order
4795     SubExprs.push_back(TheCall->getArg(1)); // Val1
4796     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
4797     SubExprs.push_back(TheCall->getArg(2)); // Val2
4798     SubExprs.push_back(TheCall->getArg(3)); // Weak
4799     break;
4800   }
4801 
4802   if (SubExprs.size() >= 2 && Form != Init) {
4803     llvm::APSInt Result(32);
4804     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
4805         !isValidOrderingForOp(Result.getSExtValue(), Op))
4806       Diag(SubExprs[1]->getBeginLoc(),
4807            diag::warn_atomic_op_has_invalid_memory_order)
4808           << SubExprs[1]->getSourceRange();
4809   }
4810 
4811   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
4812     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
4813     llvm::APSInt Result(32);
4814     if (Scope->isIntegerConstantExpr(Result, Context) &&
4815         !ScopeModel->isValid(Result.getZExtValue())) {
4816       Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
4817           << Scope->getSourceRange();
4818     }
4819     SubExprs.push_back(Scope);
4820   }
4821 
4822   AtomicExpr *AE =
4823       new (Context) AtomicExpr(TheCall->getCallee()->getBeginLoc(), SubExprs,
4824                                ResultType, Op, TheCall->getRParenLoc());
4825 
4826   if ((Op == AtomicExpr::AO__c11_atomic_load ||
4827        Op == AtomicExpr::AO__c11_atomic_store ||
4828        Op == AtomicExpr::AO__opencl_atomic_load ||
4829        Op == AtomicExpr::AO__opencl_atomic_store ) &&
4830       Context.AtomicUsesUnsupportedLibcall(AE))
4831     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
4832         << ((Op == AtomicExpr::AO__c11_atomic_load ||
4833              Op == AtomicExpr::AO__opencl_atomic_load)
4834                 ? 0
4835                 : 1);
4836 
4837   return AE;
4838 }
4839 
4840 /// checkBuiltinArgument - Given a call to a builtin function, perform
4841 /// normal type-checking on the given argument, updating the call in
4842 /// place.  This is useful when a builtin function requires custom
4843 /// type-checking for some of its arguments but not necessarily all of
4844 /// them.
4845 ///
4846 /// Returns true on error.
4847 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
4848   FunctionDecl *Fn = E->getDirectCallee();
4849   assert(Fn && "builtin call without direct callee!");
4850 
4851   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
4852   InitializedEntity Entity =
4853     InitializedEntity::InitializeParameter(S.Context, Param);
4854 
4855   ExprResult Arg = E->getArg(0);
4856   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
4857   if (Arg.isInvalid())
4858     return true;
4859 
4860   E->setArg(ArgIndex, Arg.get());
4861   return false;
4862 }
4863 
4864 /// We have a call to a function like __sync_fetch_and_add, which is an
4865 /// overloaded function based on the pointer type of its first argument.
4866 /// The main ActOnCallExpr routines have already promoted the types of
4867 /// arguments because all of these calls are prototyped as void(...).
4868 ///
4869 /// This function goes through and does final semantic checking for these
4870 /// builtins, as well as generating any warnings.
4871 ExprResult
4872 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
4873   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
4874   Expr *Callee = TheCall->getCallee();
4875   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
4876   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4877 
4878   // Ensure that we have at least one argument to do type inference from.
4879   if (TheCall->getNumArgs() < 1) {
4880     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
4881         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
4882     return ExprError();
4883   }
4884 
4885   // Inspect the first argument of the atomic builtin.  This should always be
4886   // a pointer type, whose element is an integral scalar or pointer type.
4887   // Because it is a pointer type, we don't have to worry about any implicit
4888   // casts here.
4889   // FIXME: We don't allow floating point scalars as input.
4890   Expr *FirstArg = TheCall->getArg(0);
4891   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
4892   if (FirstArgResult.isInvalid())
4893     return ExprError();
4894   FirstArg = FirstArgResult.get();
4895   TheCall->setArg(0, FirstArg);
4896 
4897   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
4898   if (!pointerType) {
4899     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
4900         << FirstArg->getType() << FirstArg->getSourceRange();
4901     return ExprError();
4902   }
4903 
4904   QualType ValType = pointerType->getPointeeType();
4905   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
4906       !ValType->isBlockPointerType()) {
4907     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
4908         << FirstArg->getType() << FirstArg->getSourceRange();
4909     return ExprError();
4910   }
4911 
4912   if (ValType.isConstQualified()) {
4913     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
4914         << FirstArg->getType() << FirstArg->getSourceRange();
4915     return ExprError();
4916   }
4917 
4918   switch (ValType.getObjCLifetime()) {
4919   case Qualifiers::OCL_None:
4920   case Qualifiers::OCL_ExplicitNone:
4921     // okay
4922     break;
4923 
4924   case Qualifiers::OCL_Weak:
4925   case Qualifiers::OCL_Strong:
4926   case Qualifiers::OCL_Autoreleasing:
4927     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
4928         << ValType << FirstArg->getSourceRange();
4929     return ExprError();
4930   }
4931 
4932   // Strip any qualifiers off ValType.
4933   ValType = ValType.getUnqualifiedType();
4934 
4935   // The majority of builtins return a value, but a few have special return
4936   // types, so allow them to override appropriately below.
4937   QualType ResultType = ValType;
4938 
4939   // We need to figure out which concrete builtin this maps onto.  For example,
4940   // __sync_fetch_and_add with a 2 byte object turns into
4941   // __sync_fetch_and_add_2.
4942 #define BUILTIN_ROW(x) \
4943   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
4944     Builtin::BI##x##_8, Builtin::BI##x##_16 }
4945 
4946   static const unsigned BuiltinIndices[][5] = {
4947     BUILTIN_ROW(__sync_fetch_and_add),
4948     BUILTIN_ROW(__sync_fetch_and_sub),
4949     BUILTIN_ROW(__sync_fetch_and_or),
4950     BUILTIN_ROW(__sync_fetch_and_and),
4951     BUILTIN_ROW(__sync_fetch_and_xor),
4952     BUILTIN_ROW(__sync_fetch_and_nand),
4953 
4954     BUILTIN_ROW(__sync_add_and_fetch),
4955     BUILTIN_ROW(__sync_sub_and_fetch),
4956     BUILTIN_ROW(__sync_and_and_fetch),
4957     BUILTIN_ROW(__sync_or_and_fetch),
4958     BUILTIN_ROW(__sync_xor_and_fetch),
4959     BUILTIN_ROW(__sync_nand_and_fetch),
4960 
4961     BUILTIN_ROW(__sync_val_compare_and_swap),
4962     BUILTIN_ROW(__sync_bool_compare_and_swap),
4963     BUILTIN_ROW(__sync_lock_test_and_set),
4964     BUILTIN_ROW(__sync_lock_release),
4965     BUILTIN_ROW(__sync_swap)
4966   };
4967 #undef BUILTIN_ROW
4968 
4969   // Determine the index of the size.
4970   unsigned SizeIndex;
4971   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
4972   case 1: SizeIndex = 0; break;
4973   case 2: SizeIndex = 1; break;
4974   case 4: SizeIndex = 2; break;
4975   case 8: SizeIndex = 3; break;
4976   case 16: SizeIndex = 4; break;
4977   default:
4978     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
4979         << FirstArg->getType() << FirstArg->getSourceRange();
4980     return ExprError();
4981   }
4982 
4983   // Each of these builtins has one pointer argument, followed by some number of
4984   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
4985   // that we ignore.  Find out which row of BuiltinIndices to read from as well
4986   // as the number of fixed args.
4987   unsigned BuiltinID = FDecl->getBuiltinID();
4988   unsigned BuiltinIndex, NumFixed = 1;
4989   bool WarnAboutSemanticsChange = false;
4990   switch (BuiltinID) {
4991   default: llvm_unreachable("Unknown overloaded atomic builtin!");
4992   case Builtin::BI__sync_fetch_and_add:
4993   case Builtin::BI__sync_fetch_and_add_1:
4994   case Builtin::BI__sync_fetch_and_add_2:
4995   case Builtin::BI__sync_fetch_and_add_4:
4996   case Builtin::BI__sync_fetch_and_add_8:
4997   case Builtin::BI__sync_fetch_and_add_16:
4998     BuiltinIndex = 0;
4999     break;
5000 
5001   case Builtin::BI__sync_fetch_and_sub:
5002   case Builtin::BI__sync_fetch_and_sub_1:
5003   case Builtin::BI__sync_fetch_and_sub_2:
5004   case Builtin::BI__sync_fetch_and_sub_4:
5005   case Builtin::BI__sync_fetch_and_sub_8:
5006   case Builtin::BI__sync_fetch_and_sub_16:
5007     BuiltinIndex = 1;
5008     break;
5009 
5010   case Builtin::BI__sync_fetch_and_or:
5011   case Builtin::BI__sync_fetch_and_or_1:
5012   case Builtin::BI__sync_fetch_and_or_2:
5013   case Builtin::BI__sync_fetch_and_or_4:
5014   case Builtin::BI__sync_fetch_and_or_8:
5015   case Builtin::BI__sync_fetch_and_or_16:
5016     BuiltinIndex = 2;
5017     break;
5018 
5019   case Builtin::BI__sync_fetch_and_and:
5020   case Builtin::BI__sync_fetch_and_and_1:
5021   case Builtin::BI__sync_fetch_and_and_2:
5022   case Builtin::BI__sync_fetch_and_and_4:
5023   case Builtin::BI__sync_fetch_and_and_8:
5024   case Builtin::BI__sync_fetch_and_and_16:
5025     BuiltinIndex = 3;
5026     break;
5027 
5028   case Builtin::BI__sync_fetch_and_xor:
5029   case Builtin::BI__sync_fetch_and_xor_1:
5030   case Builtin::BI__sync_fetch_and_xor_2:
5031   case Builtin::BI__sync_fetch_and_xor_4:
5032   case Builtin::BI__sync_fetch_and_xor_8:
5033   case Builtin::BI__sync_fetch_and_xor_16:
5034     BuiltinIndex = 4;
5035     break;
5036 
5037   case Builtin::BI__sync_fetch_and_nand:
5038   case Builtin::BI__sync_fetch_and_nand_1:
5039   case Builtin::BI__sync_fetch_and_nand_2:
5040   case Builtin::BI__sync_fetch_and_nand_4:
5041   case Builtin::BI__sync_fetch_and_nand_8:
5042   case Builtin::BI__sync_fetch_and_nand_16:
5043     BuiltinIndex = 5;
5044     WarnAboutSemanticsChange = true;
5045     break;
5046 
5047   case Builtin::BI__sync_add_and_fetch:
5048   case Builtin::BI__sync_add_and_fetch_1:
5049   case Builtin::BI__sync_add_and_fetch_2:
5050   case Builtin::BI__sync_add_and_fetch_4:
5051   case Builtin::BI__sync_add_and_fetch_8:
5052   case Builtin::BI__sync_add_and_fetch_16:
5053     BuiltinIndex = 6;
5054     break;
5055 
5056   case Builtin::BI__sync_sub_and_fetch:
5057   case Builtin::BI__sync_sub_and_fetch_1:
5058   case Builtin::BI__sync_sub_and_fetch_2:
5059   case Builtin::BI__sync_sub_and_fetch_4:
5060   case Builtin::BI__sync_sub_and_fetch_8:
5061   case Builtin::BI__sync_sub_and_fetch_16:
5062     BuiltinIndex = 7;
5063     break;
5064 
5065   case Builtin::BI__sync_and_and_fetch:
5066   case Builtin::BI__sync_and_and_fetch_1:
5067   case Builtin::BI__sync_and_and_fetch_2:
5068   case Builtin::BI__sync_and_and_fetch_4:
5069   case Builtin::BI__sync_and_and_fetch_8:
5070   case Builtin::BI__sync_and_and_fetch_16:
5071     BuiltinIndex = 8;
5072     break;
5073 
5074   case Builtin::BI__sync_or_and_fetch:
5075   case Builtin::BI__sync_or_and_fetch_1:
5076   case Builtin::BI__sync_or_and_fetch_2:
5077   case Builtin::BI__sync_or_and_fetch_4:
5078   case Builtin::BI__sync_or_and_fetch_8:
5079   case Builtin::BI__sync_or_and_fetch_16:
5080     BuiltinIndex = 9;
5081     break;
5082 
5083   case Builtin::BI__sync_xor_and_fetch:
5084   case Builtin::BI__sync_xor_and_fetch_1:
5085   case Builtin::BI__sync_xor_and_fetch_2:
5086   case Builtin::BI__sync_xor_and_fetch_4:
5087   case Builtin::BI__sync_xor_and_fetch_8:
5088   case Builtin::BI__sync_xor_and_fetch_16:
5089     BuiltinIndex = 10;
5090     break;
5091 
5092   case Builtin::BI__sync_nand_and_fetch:
5093   case Builtin::BI__sync_nand_and_fetch_1:
5094   case Builtin::BI__sync_nand_and_fetch_2:
5095   case Builtin::BI__sync_nand_and_fetch_4:
5096   case Builtin::BI__sync_nand_and_fetch_8:
5097   case Builtin::BI__sync_nand_and_fetch_16:
5098     BuiltinIndex = 11;
5099     WarnAboutSemanticsChange = true;
5100     break;
5101 
5102   case Builtin::BI__sync_val_compare_and_swap:
5103   case Builtin::BI__sync_val_compare_and_swap_1:
5104   case Builtin::BI__sync_val_compare_and_swap_2:
5105   case Builtin::BI__sync_val_compare_and_swap_4:
5106   case Builtin::BI__sync_val_compare_and_swap_8:
5107   case Builtin::BI__sync_val_compare_and_swap_16:
5108     BuiltinIndex = 12;
5109     NumFixed = 2;
5110     break;
5111 
5112   case Builtin::BI__sync_bool_compare_and_swap:
5113   case Builtin::BI__sync_bool_compare_and_swap_1:
5114   case Builtin::BI__sync_bool_compare_and_swap_2:
5115   case Builtin::BI__sync_bool_compare_and_swap_4:
5116   case Builtin::BI__sync_bool_compare_and_swap_8:
5117   case Builtin::BI__sync_bool_compare_and_swap_16:
5118     BuiltinIndex = 13;
5119     NumFixed = 2;
5120     ResultType = Context.BoolTy;
5121     break;
5122 
5123   case Builtin::BI__sync_lock_test_and_set:
5124   case Builtin::BI__sync_lock_test_and_set_1:
5125   case Builtin::BI__sync_lock_test_and_set_2:
5126   case Builtin::BI__sync_lock_test_and_set_4:
5127   case Builtin::BI__sync_lock_test_and_set_8:
5128   case Builtin::BI__sync_lock_test_and_set_16:
5129     BuiltinIndex = 14;
5130     break;
5131 
5132   case Builtin::BI__sync_lock_release:
5133   case Builtin::BI__sync_lock_release_1:
5134   case Builtin::BI__sync_lock_release_2:
5135   case Builtin::BI__sync_lock_release_4:
5136   case Builtin::BI__sync_lock_release_8:
5137   case Builtin::BI__sync_lock_release_16:
5138     BuiltinIndex = 15;
5139     NumFixed = 0;
5140     ResultType = Context.VoidTy;
5141     break;
5142 
5143   case Builtin::BI__sync_swap:
5144   case Builtin::BI__sync_swap_1:
5145   case Builtin::BI__sync_swap_2:
5146   case Builtin::BI__sync_swap_4:
5147   case Builtin::BI__sync_swap_8:
5148   case Builtin::BI__sync_swap_16:
5149     BuiltinIndex = 16;
5150     break;
5151   }
5152 
5153   // Now that we know how many fixed arguments we expect, first check that we
5154   // have at least that many.
5155   if (TheCall->getNumArgs() < 1+NumFixed) {
5156     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5157         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5158         << Callee->getSourceRange();
5159     return ExprError();
5160   }
5161 
5162   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5163       << Callee->getSourceRange();
5164 
5165   if (WarnAboutSemanticsChange) {
5166     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5167         << Callee->getSourceRange();
5168   }
5169 
5170   // Get the decl for the concrete builtin from this, we can tell what the
5171   // concrete integer type we should convert to is.
5172   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5173   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5174   FunctionDecl *NewBuiltinDecl;
5175   if (NewBuiltinID == BuiltinID)
5176     NewBuiltinDecl = FDecl;
5177   else {
5178     // Perform builtin lookup to avoid redeclaring it.
5179     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5180     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5181     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5182     assert(Res.getFoundDecl());
5183     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5184     if (!NewBuiltinDecl)
5185       return ExprError();
5186   }
5187 
5188   // The first argument --- the pointer --- has a fixed type; we
5189   // deduce the types of the rest of the arguments accordingly.  Walk
5190   // the remaining arguments, converting them to the deduced value type.
5191   for (unsigned i = 0; i != NumFixed; ++i) {
5192     ExprResult Arg = TheCall->getArg(i+1);
5193 
5194     // GCC does an implicit conversion to the pointer or integer ValType.  This
5195     // can fail in some cases (1i -> int**), check for this error case now.
5196     // Initialize the argument.
5197     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5198                                                    ValType, /*consume*/ false);
5199     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5200     if (Arg.isInvalid())
5201       return ExprError();
5202 
5203     // Okay, we have something that *can* be converted to the right type.  Check
5204     // to see if there is a potentially weird extension going on here.  This can
5205     // happen when you do an atomic operation on something like an char* and
5206     // pass in 42.  The 42 gets converted to char.  This is even more strange
5207     // for things like 45.123 -> char, etc.
5208     // FIXME: Do this check.
5209     TheCall->setArg(i+1, Arg.get());
5210   }
5211 
5212   // Create a new DeclRefExpr to refer to the new decl.
5213   DeclRefExpr* NewDRE = DeclRefExpr::Create(
5214       Context,
5215       DRE->getQualifierLoc(),
5216       SourceLocation(),
5217       NewBuiltinDecl,
5218       /*enclosing*/ false,
5219       DRE->getLocation(),
5220       Context.BuiltinFnTy,
5221       DRE->getValueKind());
5222 
5223   // Set the callee in the CallExpr.
5224   // FIXME: This loses syntactic information.
5225   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5226   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5227                                               CK_BuiltinFnToFnPtr);
5228   TheCall->setCallee(PromotedCall.get());
5229 
5230   // Change the result type of the call to match the original value type. This
5231   // is arbitrary, but the codegen for these builtins ins design to handle it
5232   // gracefully.
5233   TheCall->setType(ResultType);
5234 
5235   return TheCallResult;
5236 }
5237 
5238 /// SemaBuiltinNontemporalOverloaded - We have a call to
5239 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5240 /// overloaded function based on the pointer type of its last argument.
5241 ///
5242 /// This function goes through and does final semantic checking for these
5243 /// builtins.
5244 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5245   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5246   DeclRefExpr *DRE =
5247       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5248   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5249   unsigned BuiltinID = FDecl->getBuiltinID();
5250   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5251           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5252          "Unexpected nontemporal load/store builtin!");
5253   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5254   unsigned numArgs = isStore ? 2 : 1;
5255 
5256   // Ensure that we have the proper number of arguments.
5257   if (checkArgCount(*this, TheCall, numArgs))
5258     return ExprError();
5259 
5260   // Inspect the last argument of the nontemporal builtin.  This should always
5261   // be a pointer type, from which we imply the type of the memory access.
5262   // Because it is a pointer type, we don't have to worry about any implicit
5263   // casts here.
5264   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5265   ExprResult PointerArgResult =
5266       DefaultFunctionArrayLvalueConversion(PointerArg);
5267 
5268   if (PointerArgResult.isInvalid())
5269     return ExprError();
5270   PointerArg = PointerArgResult.get();
5271   TheCall->setArg(numArgs - 1, PointerArg);
5272 
5273   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5274   if (!pointerType) {
5275     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5276         << PointerArg->getType() << PointerArg->getSourceRange();
5277     return ExprError();
5278   }
5279 
5280   QualType ValType = pointerType->getPointeeType();
5281 
5282   // Strip any qualifiers off ValType.
5283   ValType = ValType.getUnqualifiedType();
5284   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5285       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5286       !ValType->isVectorType()) {
5287     Diag(DRE->getBeginLoc(),
5288          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5289         << PointerArg->getType() << PointerArg->getSourceRange();
5290     return ExprError();
5291   }
5292 
5293   if (!isStore) {
5294     TheCall->setType(ValType);
5295     return TheCallResult;
5296   }
5297 
5298   ExprResult ValArg = TheCall->getArg(0);
5299   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5300       Context, ValType, /*consume*/ false);
5301   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5302   if (ValArg.isInvalid())
5303     return ExprError();
5304 
5305   TheCall->setArg(0, ValArg.get());
5306   TheCall->setType(Context.VoidTy);
5307   return TheCallResult;
5308 }
5309 
5310 /// CheckObjCString - Checks that the argument to the builtin
5311 /// CFString constructor is correct
5312 /// Note: It might also make sense to do the UTF-16 conversion here (would
5313 /// simplify the backend).
5314 bool Sema::CheckObjCString(Expr *Arg) {
5315   Arg = Arg->IgnoreParenCasts();
5316   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5317 
5318   if (!Literal || !Literal->isAscii()) {
5319     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5320         << Arg->getSourceRange();
5321     return true;
5322   }
5323 
5324   if (Literal->containsNonAsciiOrNull()) {
5325     StringRef String = Literal->getString();
5326     unsigned NumBytes = String.size();
5327     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5328     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5329     llvm::UTF16 *ToPtr = &ToBuf[0];
5330 
5331     llvm::ConversionResult Result =
5332         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5333                                  ToPtr + NumBytes, llvm::strictConversion);
5334     // Check for conversion failure.
5335     if (Result != llvm::conversionOK)
5336       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5337           << Arg->getSourceRange();
5338   }
5339   return false;
5340 }
5341 
5342 /// CheckObjCString - Checks that the format string argument to the os_log()
5343 /// and os_trace() functions is correct, and converts it to const char *.
5344 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5345   Arg = Arg->IgnoreParenCasts();
5346   auto *Literal = dyn_cast<StringLiteral>(Arg);
5347   if (!Literal) {
5348     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5349       Literal = ObjcLiteral->getString();
5350     }
5351   }
5352 
5353   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5354     return ExprError(
5355         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5356         << Arg->getSourceRange());
5357   }
5358 
5359   ExprResult Result(Literal);
5360   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5361   InitializedEntity Entity =
5362       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5363   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5364   return Result;
5365 }
5366 
5367 /// Check that the user is calling the appropriate va_start builtin for the
5368 /// target and calling convention.
5369 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5370   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5371   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5372   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
5373   bool IsWindows = TT.isOSWindows();
5374   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5375   if (IsX64 || IsAArch64) {
5376     CallingConv CC = CC_C;
5377     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5378       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
5379     if (IsMSVAStart) {
5380       // Don't allow this in System V ABI functions.
5381       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5382         return S.Diag(Fn->getBeginLoc(),
5383                       diag::err_ms_va_start_used_in_sysv_function);
5384     } else {
5385       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5386       // On x64 Windows, don't allow this in System V ABI functions.
5387       // (Yes, that means there's no corresponding way to support variadic
5388       // System V ABI functions on Windows.)
5389       if ((IsWindows && CC == CC_X86_64SysV) ||
5390           (!IsWindows && CC == CC_Win64))
5391         return S.Diag(Fn->getBeginLoc(),
5392                       diag::err_va_start_used_in_wrong_abi_function)
5393                << !IsWindows;
5394     }
5395     return false;
5396   }
5397 
5398   if (IsMSVAStart)
5399     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5400   return false;
5401 }
5402 
5403 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5404                                              ParmVarDecl **LastParam = nullptr) {
5405   // Determine whether the current function, block, or obj-c method is variadic
5406   // and get its parameter list.
5407   bool IsVariadic = false;
5408   ArrayRef<ParmVarDecl *> Params;
5409   DeclContext *Caller = S.CurContext;
5410   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5411     IsVariadic = Block->isVariadic();
5412     Params = Block->parameters();
5413   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5414     IsVariadic = FD->isVariadic();
5415     Params = FD->parameters();
5416   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5417     IsVariadic = MD->isVariadic();
5418     // FIXME: This isn't correct for methods (results in bogus warning).
5419     Params = MD->parameters();
5420   } else if (isa<CapturedDecl>(Caller)) {
5421     // We don't support va_start in a CapturedDecl.
5422     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5423     return true;
5424   } else {
5425     // This must be some other declcontext that parses exprs.
5426     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5427     return true;
5428   }
5429 
5430   if (!IsVariadic) {
5431     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5432     return true;
5433   }
5434 
5435   if (LastParam)
5436     *LastParam = Params.empty() ? nullptr : Params.back();
5437 
5438   return false;
5439 }
5440 
5441 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5442 /// for validity.  Emit an error and return true on failure; return false
5443 /// on success.
5444 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5445   Expr *Fn = TheCall->getCallee();
5446 
5447   if (checkVAStartABI(*this, BuiltinID, Fn))
5448     return true;
5449 
5450   if (TheCall->getNumArgs() > 2) {
5451     Diag(TheCall->getArg(2)->getBeginLoc(),
5452          diag::err_typecheck_call_too_many_args)
5453         << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5454         << Fn->getSourceRange()
5455         << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5456                        (*(TheCall->arg_end() - 1))->getEndLoc());
5457     return true;
5458   }
5459 
5460   if (TheCall->getNumArgs() < 2) {
5461     return Diag(TheCall->getEndLoc(),
5462                 diag::err_typecheck_call_too_few_args_at_least)
5463            << 0 /*function call*/ << 2 << TheCall->getNumArgs();
5464   }
5465 
5466   // Type-check the first argument normally.
5467   if (checkBuiltinArgument(*this, TheCall, 0))
5468     return true;
5469 
5470   // Check that the current function is variadic, and get its last parameter.
5471   ParmVarDecl *LastParam;
5472   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5473     return true;
5474 
5475   // Verify that the second argument to the builtin is the last argument of the
5476   // current function or method.
5477   bool SecondArgIsLastNamedArgument = false;
5478   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5479 
5480   // These are valid if SecondArgIsLastNamedArgument is false after the next
5481   // block.
5482   QualType Type;
5483   SourceLocation ParamLoc;
5484   bool IsCRegister = false;
5485 
5486   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5487     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5488       SecondArgIsLastNamedArgument = PV == LastParam;
5489 
5490       Type = PV->getType();
5491       ParamLoc = PV->getLocation();
5492       IsCRegister =
5493           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5494     }
5495   }
5496 
5497   if (!SecondArgIsLastNamedArgument)
5498     Diag(TheCall->getArg(1)->getBeginLoc(),
5499          diag::warn_second_arg_of_va_start_not_last_named_param);
5500   else if (IsCRegister || Type->isReferenceType() ||
5501            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5502              // Promotable integers are UB, but enumerations need a bit of
5503              // extra checking to see what their promotable type actually is.
5504              if (!Type->isPromotableIntegerType())
5505                return false;
5506              if (!Type->isEnumeralType())
5507                return true;
5508              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
5509              return !(ED &&
5510                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5511            }()) {
5512     unsigned Reason = 0;
5513     if (Type->isReferenceType())  Reason = 1;
5514     else if (IsCRegister)         Reason = 2;
5515     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5516     Diag(ParamLoc, diag::note_parameter_type) << Type;
5517   }
5518 
5519   TheCall->setType(Context.VoidTy);
5520   return false;
5521 }
5522 
5523 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5524   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5525   //                 const char *named_addr);
5526 
5527   Expr *Func = Call->getCallee();
5528 
5529   if (Call->getNumArgs() < 3)
5530     return Diag(Call->getEndLoc(),
5531                 diag::err_typecheck_call_too_few_args_at_least)
5532            << 0 /*function call*/ << 3 << Call->getNumArgs();
5533 
5534   // Type-check the first argument normally.
5535   if (checkBuiltinArgument(*this, Call, 0))
5536     return true;
5537 
5538   // Check that the current function is variadic.
5539   if (checkVAStartIsInVariadicFunction(*this, Func))
5540     return true;
5541 
5542   // __va_start on Windows does not validate the parameter qualifiers
5543 
5544   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5545   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5546 
5547   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5548   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5549 
5550   const QualType &ConstCharPtrTy =
5551       Context.getPointerType(Context.CharTy.withConst());
5552   if (!Arg1Ty->isPointerType() ||
5553       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5554     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5555         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5556         << 0                                      /* qualifier difference */
5557         << 3                                      /* parameter mismatch */
5558         << 2 << Arg1->getType() << ConstCharPtrTy;
5559 
5560   const QualType SizeTy = Context.getSizeType();
5561   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5562     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5563         << Arg2->getType() << SizeTy << 1 /* different class */
5564         << 0                              /* qualifier difference */
5565         << 3                              /* parameter mismatch */
5566         << 3 << Arg2->getType() << SizeTy;
5567 
5568   return false;
5569 }
5570 
5571 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5572 /// friends.  This is declared to take (...), so we have to check everything.
5573 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5574   if (TheCall->getNumArgs() < 2)
5575     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5576            << 0 << 2 << TheCall->getNumArgs() /*function call*/;
5577   if (TheCall->getNumArgs() > 2)
5578     return Diag(TheCall->getArg(2)->getBeginLoc(),
5579                 diag::err_typecheck_call_too_many_args)
5580            << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5581            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5582                           (*(TheCall->arg_end() - 1))->getEndLoc());
5583 
5584   ExprResult OrigArg0 = TheCall->getArg(0);
5585   ExprResult OrigArg1 = TheCall->getArg(1);
5586 
5587   // Do standard promotions between the two arguments, returning their common
5588   // type.
5589   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
5590   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5591     return true;
5592 
5593   // Make sure any conversions are pushed back into the call; this is
5594   // type safe since unordered compare builtins are declared as "_Bool
5595   // foo(...)".
5596   TheCall->setArg(0, OrigArg0.get());
5597   TheCall->setArg(1, OrigArg1.get());
5598 
5599   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5600     return false;
5601 
5602   // If the common type isn't a real floating type, then the arguments were
5603   // invalid for this operation.
5604   if (Res.isNull() || !Res->isRealFloatingType())
5605     return Diag(OrigArg0.get()->getBeginLoc(),
5606                 diag::err_typecheck_call_invalid_ordered_compare)
5607            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5608            << SourceRange(OrigArg0.get()->getBeginLoc(),
5609                           OrigArg1.get()->getEndLoc());
5610 
5611   return false;
5612 }
5613 
5614 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5615 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5616 /// to check everything. We expect the last argument to be a floating point
5617 /// value.
5618 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5619   if (TheCall->getNumArgs() < NumArgs)
5620     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5621            << 0 << NumArgs << TheCall->getNumArgs() /*function call*/;
5622   if (TheCall->getNumArgs() > NumArgs)
5623     return Diag(TheCall->getArg(NumArgs)->getBeginLoc(),
5624                 diag::err_typecheck_call_too_many_args)
5625            << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
5626            << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(),
5627                           (*(TheCall->arg_end() - 1))->getEndLoc());
5628 
5629   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5630 
5631   if (OrigArg->isTypeDependent())
5632     return false;
5633 
5634   // This operation requires a non-_Complex floating-point number.
5635   if (!OrigArg->getType()->isRealFloatingType())
5636     return Diag(OrigArg->getBeginLoc(),
5637                 diag::err_typecheck_call_invalid_unary_fp)
5638            << OrigArg->getType() << OrigArg->getSourceRange();
5639 
5640   // If this is an implicit conversion from float -> float, double, or
5641   // long double, remove it.
5642   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
5643     // Only remove standard FloatCasts, leaving other casts inplace
5644     if (Cast->getCastKind() == CK_FloatingCast) {
5645       Expr *CastArg = Cast->getSubExpr();
5646       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
5647         assert(
5648             (Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
5649              Cast->getType()->isSpecificBuiltinType(BuiltinType::Float) ||
5650              Cast->getType()->isSpecificBuiltinType(BuiltinType::LongDouble)) &&
5651             "promotion from float to either float, double, or long double is "
5652             "the only expected cast here");
5653         Cast->setSubExpr(nullptr);
5654         TheCall->setArg(NumArgs-1, CastArg);
5655       }
5656     }
5657   }
5658 
5659   return false;
5660 }
5661 
5662 // Customized Sema Checking for VSX builtins that have the following signature:
5663 // vector [...] builtinName(vector [...], vector [...], const int);
5664 // Which takes the same type of vectors (any legal vector type) for the first
5665 // two arguments and takes compile time constant for the third argument.
5666 // Example builtins are :
5667 // vector double vec_xxpermdi(vector double, vector double, int);
5668 // vector short vec_xxsldwi(vector short, vector short, int);
5669 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
5670   unsigned ExpectedNumArgs = 3;
5671   if (TheCall->getNumArgs() < ExpectedNumArgs)
5672     return Diag(TheCall->getEndLoc(),
5673                 diag::err_typecheck_call_too_few_args_at_least)
5674            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5675            << TheCall->getSourceRange();
5676 
5677   if (TheCall->getNumArgs() > ExpectedNumArgs)
5678     return Diag(TheCall->getEndLoc(),
5679                 diag::err_typecheck_call_too_many_args_at_most)
5680            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
5681            << TheCall->getSourceRange();
5682 
5683   // Check the third argument is a compile time constant
5684   llvm::APSInt Value;
5685   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
5686     return Diag(TheCall->getBeginLoc(),
5687                 diag::err_vsx_builtin_nonconstant_argument)
5688            << 3 /* argument index */ << TheCall->getDirectCallee()
5689            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
5690                           TheCall->getArg(2)->getEndLoc());
5691 
5692   QualType Arg1Ty = TheCall->getArg(0)->getType();
5693   QualType Arg2Ty = TheCall->getArg(1)->getType();
5694 
5695   // Check the type of argument 1 and argument 2 are vectors.
5696   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
5697   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
5698       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
5699     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
5700            << TheCall->getDirectCallee()
5701            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5702                           TheCall->getArg(1)->getEndLoc());
5703   }
5704 
5705   // Check the first two arguments are the same type.
5706   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
5707     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
5708            << TheCall->getDirectCallee()
5709            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5710                           TheCall->getArg(1)->getEndLoc());
5711   }
5712 
5713   // When default clang type checking is turned off and the customized type
5714   // checking is used, the returning type of the function must be explicitly
5715   // set. Otherwise it is _Bool by default.
5716   TheCall->setType(Arg1Ty);
5717 
5718   return false;
5719 }
5720 
5721 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
5722 // This is declared to take (...), so we have to check everything.
5723 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
5724   if (TheCall->getNumArgs() < 2)
5725     return ExprError(Diag(TheCall->getEndLoc(),
5726                           diag::err_typecheck_call_too_few_args_at_least)
5727                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
5728                      << TheCall->getSourceRange());
5729 
5730   // Determine which of the following types of shufflevector we're checking:
5731   // 1) unary, vector mask: (lhs, mask)
5732   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
5733   QualType resType = TheCall->getArg(0)->getType();
5734   unsigned numElements = 0;
5735 
5736   if (!TheCall->getArg(0)->isTypeDependent() &&
5737       !TheCall->getArg(1)->isTypeDependent()) {
5738     QualType LHSType = TheCall->getArg(0)->getType();
5739     QualType RHSType = TheCall->getArg(1)->getType();
5740 
5741     if (!LHSType->isVectorType() || !RHSType->isVectorType())
5742       return ExprError(
5743           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
5744           << TheCall->getDirectCallee()
5745           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5746                          TheCall->getArg(1)->getEndLoc()));
5747 
5748     numElements = LHSType->getAs<VectorType>()->getNumElements();
5749     unsigned numResElements = TheCall->getNumArgs() - 2;
5750 
5751     // Check to see if we have a call with 2 vector arguments, the unary shuffle
5752     // with mask.  If so, verify that RHS is an integer vector type with the
5753     // same number of elts as lhs.
5754     if (TheCall->getNumArgs() == 2) {
5755       if (!RHSType->hasIntegerRepresentation() ||
5756           RHSType->getAs<VectorType>()->getNumElements() != numElements)
5757         return ExprError(Diag(TheCall->getBeginLoc(),
5758                               diag::err_vec_builtin_incompatible_vector)
5759                          << TheCall->getDirectCallee()
5760                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
5761                                         TheCall->getArg(1)->getEndLoc()));
5762     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
5763       return ExprError(Diag(TheCall->getBeginLoc(),
5764                             diag::err_vec_builtin_incompatible_vector)
5765                        << TheCall->getDirectCallee()
5766                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
5767                                       TheCall->getArg(1)->getEndLoc()));
5768     } else if (numElements != numResElements) {
5769       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
5770       resType = Context.getVectorType(eltType, numResElements,
5771                                       VectorType::GenericVector);
5772     }
5773   }
5774 
5775   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
5776     if (TheCall->getArg(i)->isTypeDependent() ||
5777         TheCall->getArg(i)->isValueDependent())
5778       continue;
5779 
5780     llvm::APSInt Result(32);
5781     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
5782       return ExprError(Diag(TheCall->getBeginLoc(),
5783                             diag::err_shufflevector_nonconstant_argument)
5784                        << TheCall->getArg(i)->getSourceRange());
5785 
5786     // Allow -1 which will be translated to undef in the IR.
5787     if (Result.isSigned() && Result.isAllOnesValue())
5788       continue;
5789 
5790     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
5791       return ExprError(Diag(TheCall->getBeginLoc(),
5792                             diag::err_shufflevector_argument_too_large)
5793                        << TheCall->getArg(i)->getSourceRange());
5794   }
5795 
5796   SmallVector<Expr*, 32> exprs;
5797 
5798   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
5799     exprs.push_back(TheCall->getArg(i));
5800     TheCall->setArg(i, nullptr);
5801   }
5802 
5803   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
5804                                          TheCall->getCallee()->getBeginLoc(),
5805                                          TheCall->getRParenLoc());
5806 }
5807 
5808 /// SemaConvertVectorExpr - Handle __builtin_convertvector
5809 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
5810                                        SourceLocation BuiltinLoc,
5811                                        SourceLocation RParenLoc) {
5812   ExprValueKind VK = VK_RValue;
5813   ExprObjectKind OK = OK_Ordinary;
5814   QualType DstTy = TInfo->getType();
5815   QualType SrcTy = E->getType();
5816 
5817   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
5818     return ExprError(Diag(BuiltinLoc,
5819                           diag::err_convertvector_non_vector)
5820                      << E->getSourceRange());
5821   if (!DstTy->isVectorType() && !DstTy->isDependentType())
5822     return ExprError(Diag(BuiltinLoc,
5823                           diag::err_convertvector_non_vector_type));
5824 
5825   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
5826     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
5827     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
5828     if (SrcElts != DstElts)
5829       return ExprError(Diag(BuiltinLoc,
5830                             diag::err_convertvector_incompatible_vector)
5831                        << E->getSourceRange());
5832   }
5833 
5834   return new (Context)
5835       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5836 }
5837 
5838 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
5839 // This is declared to take (const void*, ...) and can take two
5840 // optional constant int args.
5841 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
5842   unsigned NumArgs = TheCall->getNumArgs();
5843 
5844   if (NumArgs > 3)
5845     return Diag(TheCall->getEndLoc(),
5846                 diag::err_typecheck_call_too_many_args_at_most)
5847            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5848 
5849   // Argument 0 is checked for us and the remaining arguments must be
5850   // constant integers.
5851   for (unsigned i = 1; i != NumArgs; ++i)
5852     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
5853       return true;
5854 
5855   return false;
5856 }
5857 
5858 /// SemaBuiltinAssume - Handle __assume (MS Extension).
5859 // __assume does not evaluate its arguments, and should warn if its argument
5860 // has side effects.
5861 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
5862   Expr *Arg = TheCall->getArg(0);
5863   if (Arg->isInstantiationDependent()) return false;
5864 
5865   if (Arg->HasSideEffects(Context))
5866     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
5867         << Arg->getSourceRange()
5868         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
5869 
5870   return false;
5871 }
5872 
5873 /// Handle __builtin_alloca_with_align. This is declared
5874 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
5875 /// than 8.
5876 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
5877   // The alignment must be a constant integer.
5878   Expr *Arg = TheCall->getArg(1);
5879 
5880   // We can't check the value of a dependent argument.
5881   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5882     if (const auto *UE =
5883             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
5884       if (UE->getKind() == UETT_AlignOf ||
5885           UE->getKind() == UETT_PreferredAlignOf)
5886         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
5887             << Arg->getSourceRange();
5888 
5889     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
5890 
5891     if (!Result.isPowerOf2())
5892       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5893              << Arg->getSourceRange();
5894 
5895     if (Result < Context.getCharWidth())
5896       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
5897              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
5898 
5899     if (Result > std::numeric_limits<int32_t>::max())
5900       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
5901              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
5902   }
5903 
5904   return false;
5905 }
5906 
5907 /// Handle __builtin_assume_aligned. This is declared
5908 /// as (const void*, size_t, ...) and can take one optional constant int arg.
5909 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
5910   unsigned NumArgs = TheCall->getNumArgs();
5911 
5912   if (NumArgs > 3)
5913     return Diag(TheCall->getEndLoc(),
5914                 diag::err_typecheck_call_too_many_args_at_most)
5915            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
5916 
5917   // The alignment must be a constant integer.
5918   Expr *Arg = TheCall->getArg(1);
5919 
5920   // We can't check the value of a dependent argument.
5921   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
5922     llvm::APSInt Result;
5923     if (SemaBuiltinConstantArg(TheCall, 1, Result))
5924       return true;
5925 
5926     if (!Result.isPowerOf2())
5927       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
5928              << Arg->getSourceRange();
5929   }
5930 
5931   if (NumArgs > 2) {
5932     ExprResult Arg(TheCall->getArg(2));
5933     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5934       Context.getSizeType(), false);
5935     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5936     if (Arg.isInvalid()) return true;
5937     TheCall->setArg(2, Arg.get());
5938   }
5939 
5940   return false;
5941 }
5942 
5943 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
5944   unsigned BuiltinID =
5945       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
5946   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
5947 
5948   unsigned NumArgs = TheCall->getNumArgs();
5949   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
5950   if (NumArgs < NumRequiredArgs) {
5951     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
5952            << 0 /* function call */ << NumRequiredArgs << NumArgs
5953            << TheCall->getSourceRange();
5954   }
5955   if (NumArgs >= NumRequiredArgs + 0x100) {
5956     return Diag(TheCall->getEndLoc(),
5957                 diag::err_typecheck_call_too_many_args_at_most)
5958            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
5959            << TheCall->getSourceRange();
5960   }
5961   unsigned i = 0;
5962 
5963   // For formatting call, check buffer arg.
5964   if (!IsSizeCall) {
5965     ExprResult Arg(TheCall->getArg(i));
5966     InitializedEntity Entity = InitializedEntity::InitializeParameter(
5967         Context, Context.VoidPtrTy, false);
5968     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5969     if (Arg.isInvalid())
5970       return true;
5971     TheCall->setArg(i, Arg.get());
5972     i++;
5973   }
5974 
5975   // Check string literal arg.
5976   unsigned FormatIdx = i;
5977   {
5978     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
5979     if (Arg.isInvalid())
5980       return true;
5981     TheCall->setArg(i, Arg.get());
5982     i++;
5983   }
5984 
5985   // Make sure variadic args are scalar.
5986   unsigned FirstDataArg = i;
5987   while (i < NumArgs) {
5988     ExprResult Arg = DefaultVariadicArgumentPromotion(
5989         TheCall->getArg(i), VariadicFunction, nullptr);
5990     if (Arg.isInvalid())
5991       return true;
5992     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
5993     if (ArgSize.getQuantity() >= 0x100) {
5994       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
5995              << i << (int)ArgSize.getQuantity() << 0xff
5996              << TheCall->getSourceRange();
5997     }
5998     TheCall->setArg(i, Arg.get());
5999     i++;
6000   }
6001 
6002   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6003   // call to avoid duplicate diagnostics.
6004   if (!IsSizeCall) {
6005     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6006     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6007     bool Success = CheckFormatArguments(
6008         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6009         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6010         CheckedVarArgs);
6011     if (!Success)
6012       return true;
6013   }
6014 
6015   if (IsSizeCall) {
6016     TheCall->setType(Context.getSizeType());
6017   } else {
6018     TheCall->setType(Context.VoidPtrTy);
6019   }
6020   return false;
6021 }
6022 
6023 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6024 /// TheCall is a constant expression.
6025 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6026                                   llvm::APSInt &Result) {
6027   Expr *Arg = TheCall->getArg(ArgNum);
6028   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6029   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6030 
6031   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6032 
6033   if (!Arg->isIntegerConstantExpr(Result, Context))
6034     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6035            << FDecl->getDeclName() << Arg->getSourceRange();
6036 
6037   return false;
6038 }
6039 
6040 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6041 /// TheCall is a constant expression in the range [Low, High].
6042 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6043                                        int Low, int High, bool RangeIsError) {
6044   llvm::APSInt Result;
6045 
6046   // We can't check the value of a dependent argument.
6047   Expr *Arg = TheCall->getArg(ArgNum);
6048   if (Arg->isTypeDependent() || Arg->isValueDependent())
6049     return false;
6050 
6051   // Check constant-ness first.
6052   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6053     return true;
6054 
6055   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6056     if (RangeIsError)
6057       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6058              << Result.toString(10) << Low << High << Arg->getSourceRange();
6059     else
6060       // Defer the warning until we know if the code will be emitted so that
6061       // dead code can ignore this.
6062       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6063                           PDiag(diag::warn_argument_invalid_range)
6064                               << Result.toString(10) << Low << High
6065                               << Arg->getSourceRange());
6066   }
6067 
6068   return false;
6069 }
6070 
6071 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6072 /// TheCall is a constant expression is a multiple of Num..
6073 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6074                                           unsigned Num) {
6075   llvm::APSInt Result;
6076 
6077   // We can't check the value of a dependent argument.
6078   Expr *Arg = TheCall->getArg(ArgNum);
6079   if (Arg->isTypeDependent() || Arg->isValueDependent())
6080     return false;
6081 
6082   // Check constant-ness first.
6083   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6084     return true;
6085 
6086   if (Result.getSExtValue() % Num != 0)
6087     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6088            << Num << Arg->getSourceRange();
6089 
6090   return false;
6091 }
6092 
6093 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6094 /// TheCall is an ARM/AArch64 special register string literal.
6095 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6096                                     int ArgNum, unsigned ExpectedFieldNum,
6097                                     bool AllowName) {
6098   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6099                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6100                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6101                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6102                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6103                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6104   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6105                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6106                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6107                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6108                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6109                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6110   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6111 
6112   // We can't check the value of a dependent argument.
6113   Expr *Arg = TheCall->getArg(ArgNum);
6114   if (Arg->isTypeDependent() || Arg->isValueDependent())
6115     return false;
6116 
6117   // Check if the argument is a string literal.
6118   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6119     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6120            << Arg->getSourceRange();
6121 
6122   // Check the type of special register given.
6123   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6124   SmallVector<StringRef, 6> Fields;
6125   Reg.split(Fields, ":");
6126 
6127   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6128     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6129            << Arg->getSourceRange();
6130 
6131   // If the string is the name of a register then we cannot check that it is
6132   // valid here but if the string is of one the forms described in ACLE then we
6133   // can check that the supplied fields are integers and within the valid
6134   // ranges.
6135   if (Fields.size() > 1) {
6136     bool FiveFields = Fields.size() == 5;
6137 
6138     bool ValidString = true;
6139     if (IsARMBuiltin) {
6140       ValidString &= Fields[0].startswith_lower("cp") ||
6141                      Fields[0].startswith_lower("p");
6142       if (ValidString)
6143         Fields[0] =
6144           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6145 
6146       ValidString &= Fields[2].startswith_lower("c");
6147       if (ValidString)
6148         Fields[2] = Fields[2].drop_front(1);
6149 
6150       if (FiveFields) {
6151         ValidString &= Fields[3].startswith_lower("c");
6152         if (ValidString)
6153           Fields[3] = Fields[3].drop_front(1);
6154       }
6155     }
6156 
6157     SmallVector<int, 5> Ranges;
6158     if (FiveFields)
6159       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6160     else
6161       Ranges.append({15, 7, 15});
6162 
6163     for (unsigned i=0; i<Fields.size(); ++i) {
6164       int IntField;
6165       ValidString &= !Fields[i].getAsInteger(10, IntField);
6166       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6167     }
6168 
6169     if (!ValidString)
6170       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6171              << Arg->getSourceRange();
6172   } else if (IsAArch64Builtin && Fields.size() == 1) {
6173     // If the register name is one of those that appear in the condition below
6174     // and the special register builtin being used is one of the write builtins,
6175     // then we require that the argument provided for writing to the register
6176     // is an integer constant expression. This is because it will be lowered to
6177     // an MSR (immediate) instruction, so we need to know the immediate at
6178     // compile time.
6179     if (TheCall->getNumArgs() != 2)
6180       return false;
6181 
6182     std::string RegLower = Reg.lower();
6183     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6184         RegLower != "pan" && RegLower != "uao")
6185       return false;
6186 
6187     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6188   }
6189 
6190   return false;
6191 }
6192 
6193 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6194 /// This checks that the target supports __builtin_longjmp and
6195 /// that val is a constant 1.
6196 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6197   if (!Context.getTargetInfo().hasSjLjLowering())
6198     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6199            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6200 
6201   Expr *Arg = TheCall->getArg(1);
6202   llvm::APSInt Result;
6203 
6204   // TODO: This is less than ideal. Overload this to take a value.
6205   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6206     return true;
6207 
6208   if (Result != 1)
6209     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6210            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6211 
6212   return false;
6213 }
6214 
6215 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6216 /// This checks that the target supports __builtin_setjmp.
6217 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6218   if (!Context.getTargetInfo().hasSjLjLowering())
6219     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6220            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6221   return false;
6222 }
6223 
6224 namespace {
6225 
6226 class UncoveredArgHandler {
6227   enum { Unknown = -1, AllCovered = -2 };
6228 
6229   signed FirstUncoveredArg = Unknown;
6230   SmallVector<const Expr *, 4> DiagnosticExprs;
6231 
6232 public:
6233   UncoveredArgHandler() = default;
6234 
6235   bool hasUncoveredArg() const {
6236     return (FirstUncoveredArg >= 0);
6237   }
6238 
6239   unsigned getUncoveredArg() const {
6240     assert(hasUncoveredArg() && "no uncovered argument");
6241     return FirstUncoveredArg;
6242   }
6243 
6244   void setAllCovered() {
6245     // A string has been found with all arguments covered, so clear out
6246     // the diagnostics.
6247     DiagnosticExprs.clear();
6248     FirstUncoveredArg = AllCovered;
6249   }
6250 
6251   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6252     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6253 
6254     // Don't update if a previous string covers all arguments.
6255     if (FirstUncoveredArg == AllCovered)
6256       return;
6257 
6258     // UncoveredArgHandler tracks the highest uncovered argument index
6259     // and with it all the strings that match this index.
6260     if (NewFirstUncoveredArg == FirstUncoveredArg)
6261       DiagnosticExprs.push_back(StrExpr);
6262     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6263       DiagnosticExprs.clear();
6264       DiagnosticExprs.push_back(StrExpr);
6265       FirstUncoveredArg = NewFirstUncoveredArg;
6266     }
6267   }
6268 
6269   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6270 };
6271 
6272 enum StringLiteralCheckType {
6273   SLCT_NotALiteral,
6274   SLCT_UncheckedLiteral,
6275   SLCT_CheckedLiteral
6276 };
6277 
6278 } // namespace
6279 
6280 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6281                                      BinaryOperatorKind BinOpKind,
6282                                      bool AddendIsRight) {
6283   unsigned BitWidth = Offset.getBitWidth();
6284   unsigned AddendBitWidth = Addend.getBitWidth();
6285   // There might be negative interim results.
6286   if (Addend.isUnsigned()) {
6287     Addend = Addend.zext(++AddendBitWidth);
6288     Addend.setIsSigned(true);
6289   }
6290   // Adjust the bit width of the APSInts.
6291   if (AddendBitWidth > BitWidth) {
6292     Offset = Offset.sext(AddendBitWidth);
6293     BitWidth = AddendBitWidth;
6294   } else if (BitWidth > AddendBitWidth) {
6295     Addend = Addend.sext(BitWidth);
6296   }
6297 
6298   bool Ov = false;
6299   llvm::APSInt ResOffset = Offset;
6300   if (BinOpKind == BO_Add)
6301     ResOffset = Offset.sadd_ov(Addend, Ov);
6302   else {
6303     assert(AddendIsRight && BinOpKind == BO_Sub &&
6304            "operator must be add or sub with addend on the right");
6305     ResOffset = Offset.ssub_ov(Addend, Ov);
6306   }
6307 
6308   // We add an offset to a pointer here so we should support an offset as big as
6309   // possible.
6310   if (Ov) {
6311     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6312            "index (intermediate) result too big");
6313     Offset = Offset.sext(2 * BitWidth);
6314     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6315     return;
6316   }
6317 
6318   Offset = ResOffset;
6319 }
6320 
6321 namespace {
6322 
6323 // This is a wrapper class around StringLiteral to support offsetted string
6324 // literals as format strings. It takes the offset into account when returning
6325 // the string and its length or the source locations to display notes correctly.
6326 class FormatStringLiteral {
6327   const StringLiteral *FExpr;
6328   int64_t Offset;
6329 
6330  public:
6331   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6332       : FExpr(fexpr), Offset(Offset) {}
6333 
6334   StringRef getString() const {
6335     return FExpr->getString().drop_front(Offset);
6336   }
6337 
6338   unsigned getByteLength() const {
6339     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6340   }
6341 
6342   unsigned getLength() const { return FExpr->getLength() - Offset; }
6343   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
6344 
6345   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
6346 
6347   QualType getType() const { return FExpr->getType(); }
6348 
6349   bool isAscii() const { return FExpr->isAscii(); }
6350   bool isWide() const { return FExpr->isWide(); }
6351   bool isUTF8() const { return FExpr->isUTF8(); }
6352   bool isUTF16() const { return FExpr->isUTF16(); }
6353   bool isUTF32() const { return FExpr->isUTF32(); }
6354   bool isPascal() const { return FExpr->isPascal(); }
6355 
6356   SourceLocation getLocationOfByte(
6357       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
6358       const TargetInfo &Target, unsigned *StartToken = nullptr,
6359       unsigned *StartTokenByteOffset = nullptr) const {
6360     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
6361                                     StartToken, StartTokenByteOffset);
6362   }
6363 
6364   SourceLocation getBeginLoc() const LLVM_READONLY {
6365     return FExpr->getBeginLoc().getLocWithOffset(Offset);
6366   }
6367 
6368   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
6369 };
6370 
6371 }  // namespace
6372 
6373 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6374                               const Expr *OrigFormatExpr,
6375                               ArrayRef<const Expr *> Args,
6376                               bool HasVAListArg, unsigned format_idx,
6377                               unsigned firstDataArg,
6378                               Sema::FormatStringType Type,
6379                               bool inFunctionCall,
6380                               Sema::VariadicCallType CallType,
6381                               llvm::SmallBitVector &CheckedVarArgs,
6382                               UncoveredArgHandler &UncoveredArg);
6383 
6384 // Determine if an expression is a string literal or constant string.
6385 // If this function returns false on the arguments to a function expecting a
6386 // format string, we will usually need to emit a warning.
6387 // True string literals are then checked by CheckFormatString.
6388 static StringLiteralCheckType
6389 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
6390                       bool HasVAListArg, unsigned format_idx,
6391                       unsigned firstDataArg, Sema::FormatStringType Type,
6392                       Sema::VariadicCallType CallType, bool InFunctionCall,
6393                       llvm::SmallBitVector &CheckedVarArgs,
6394                       UncoveredArgHandler &UncoveredArg,
6395                       llvm::APSInt Offset) {
6396  tryAgain:
6397   assert(Offset.isSigned() && "invalid offset");
6398 
6399   if (E->isTypeDependent() || E->isValueDependent())
6400     return SLCT_NotALiteral;
6401 
6402   E = E->IgnoreParenCasts();
6403 
6404   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
6405     // Technically -Wformat-nonliteral does not warn about this case.
6406     // The behavior of printf and friends in this case is implementation
6407     // dependent.  Ideally if the format string cannot be null then
6408     // it should have a 'nonnull' attribute in the function prototype.
6409     return SLCT_UncheckedLiteral;
6410 
6411   switch (E->getStmtClass()) {
6412   case Stmt::BinaryConditionalOperatorClass:
6413   case Stmt::ConditionalOperatorClass: {
6414     // The expression is a literal if both sub-expressions were, and it was
6415     // completely checked only if both sub-expressions were checked.
6416     const AbstractConditionalOperator *C =
6417         cast<AbstractConditionalOperator>(E);
6418 
6419     // Determine whether it is necessary to check both sub-expressions, for
6420     // example, because the condition expression is a constant that can be
6421     // evaluated at compile time.
6422     bool CheckLeft = true, CheckRight = true;
6423 
6424     bool Cond;
6425     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
6426       if (Cond)
6427         CheckRight = false;
6428       else
6429         CheckLeft = false;
6430     }
6431 
6432     // We need to maintain the offsets for the right and the left hand side
6433     // separately to check if every possible indexed expression is a valid
6434     // string literal. They might have different offsets for different string
6435     // literals in the end.
6436     StringLiteralCheckType Left;
6437     if (!CheckLeft)
6438       Left = SLCT_UncheckedLiteral;
6439     else {
6440       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
6441                                    HasVAListArg, format_idx, firstDataArg,
6442                                    Type, CallType, InFunctionCall,
6443                                    CheckedVarArgs, UncoveredArg, Offset);
6444       if (Left == SLCT_NotALiteral || !CheckRight) {
6445         return Left;
6446       }
6447     }
6448 
6449     StringLiteralCheckType Right =
6450         checkFormatStringExpr(S, C->getFalseExpr(), Args,
6451                               HasVAListArg, format_idx, firstDataArg,
6452                               Type, CallType, InFunctionCall, CheckedVarArgs,
6453                               UncoveredArg, Offset);
6454 
6455     return (CheckLeft && Left < Right) ? Left : Right;
6456   }
6457 
6458   case Stmt::ImplicitCastExprClass:
6459     E = cast<ImplicitCastExpr>(E)->getSubExpr();
6460     goto tryAgain;
6461 
6462   case Stmt::OpaqueValueExprClass:
6463     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
6464       E = src;
6465       goto tryAgain;
6466     }
6467     return SLCT_NotALiteral;
6468 
6469   case Stmt::PredefinedExprClass:
6470     // While __func__, etc., are technically not string literals, they
6471     // cannot contain format specifiers and thus are not a security
6472     // liability.
6473     return SLCT_UncheckedLiteral;
6474 
6475   case Stmt::DeclRefExprClass: {
6476     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6477 
6478     // As an exception, do not flag errors for variables binding to
6479     // const string literals.
6480     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
6481       bool isConstant = false;
6482       QualType T = DR->getType();
6483 
6484       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
6485         isConstant = AT->getElementType().isConstant(S.Context);
6486       } else if (const PointerType *PT = T->getAs<PointerType>()) {
6487         isConstant = T.isConstant(S.Context) &&
6488                      PT->getPointeeType().isConstant(S.Context);
6489       } else if (T->isObjCObjectPointerType()) {
6490         // In ObjC, there is usually no "const ObjectPointer" type,
6491         // so don't check if the pointee type is constant.
6492         isConstant = T.isConstant(S.Context);
6493       }
6494 
6495       if (isConstant) {
6496         if (const Expr *Init = VD->getAnyInitializer()) {
6497           // Look through initializers like const char c[] = { "foo" }
6498           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
6499             if (InitList->isStringLiteralInit())
6500               Init = InitList->getInit(0)->IgnoreParenImpCasts();
6501           }
6502           return checkFormatStringExpr(S, Init, Args,
6503                                        HasVAListArg, format_idx,
6504                                        firstDataArg, Type, CallType,
6505                                        /*InFunctionCall*/ false, CheckedVarArgs,
6506                                        UncoveredArg, Offset);
6507         }
6508       }
6509 
6510       // For vprintf* functions (i.e., HasVAListArg==true), we add a
6511       // special check to see if the format string is a function parameter
6512       // of the function calling the printf function.  If the function
6513       // has an attribute indicating it is a printf-like function, then we
6514       // should suppress warnings concerning non-literals being used in a call
6515       // to a vprintf function.  For example:
6516       //
6517       // void
6518       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
6519       //      va_list ap;
6520       //      va_start(ap, fmt);
6521       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
6522       //      ...
6523       // }
6524       if (HasVAListArg) {
6525         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
6526           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
6527             int PVIndex = PV->getFunctionScopeIndex() + 1;
6528             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
6529               // adjust for implicit parameter
6530               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
6531                 if (MD->isInstance())
6532                   ++PVIndex;
6533               // We also check if the formats are compatible.
6534               // We can't pass a 'scanf' string to a 'printf' function.
6535               if (PVIndex == PVFormat->getFormatIdx() &&
6536                   Type == S.GetFormatStringType(PVFormat))
6537                 return SLCT_UncheckedLiteral;
6538             }
6539           }
6540         }
6541       }
6542     }
6543 
6544     return SLCT_NotALiteral;
6545   }
6546 
6547   case Stmt::CallExprClass:
6548   case Stmt::CXXMemberCallExprClass: {
6549     const CallExpr *CE = cast<CallExpr>(E);
6550     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
6551       bool IsFirst = true;
6552       StringLiteralCheckType CommonResult;
6553       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
6554         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
6555         StringLiteralCheckType Result = checkFormatStringExpr(
6556             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6557             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6558         if (IsFirst) {
6559           CommonResult = Result;
6560           IsFirst = false;
6561         }
6562       }
6563       if (!IsFirst)
6564         return CommonResult;
6565 
6566       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
6567         unsigned BuiltinID = FD->getBuiltinID();
6568         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6569             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
6570           const Expr *Arg = CE->getArg(0);
6571           return checkFormatStringExpr(S, Arg, Args,
6572                                        HasVAListArg, format_idx,
6573                                        firstDataArg, Type, CallType,
6574                                        InFunctionCall, CheckedVarArgs,
6575                                        UncoveredArg, Offset);
6576         }
6577       }
6578     }
6579 
6580     return SLCT_NotALiteral;
6581   }
6582   case Stmt::ObjCMessageExprClass: {
6583     const auto *ME = cast<ObjCMessageExpr>(E);
6584     if (const auto *ND = ME->getMethodDecl()) {
6585       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
6586         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
6587         return checkFormatStringExpr(
6588             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
6589             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
6590       }
6591     }
6592 
6593     return SLCT_NotALiteral;
6594   }
6595   case Stmt::ObjCStringLiteralClass:
6596   case Stmt::StringLiteralClass: {
6597     const StringLiteral *StrE = nullptr;
6598 
6599     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
6600       StrE = ObjCFExpr->getString();
6601     else
6602       StrE = cast<StringLiteral>(E);
6603 
6604     if (StrE) {
6605       if (Offset.isNegative() || Offset > StrE->getLength()) {
6606         // TODO: It would be better to have an explicit warning for out of
6607         // bounds literals.
6608         return SLCT_NotALiteral;
6609       }
6610       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
6611       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
6612                         firstDataArg, Type, InFunctionCall, CallType,
6613                         CheckedVarArgs, UncoveredArg);
6614       return SLCT_CheckedLiteral;
6615     }
6616 
6617     return SLCT_NotALiteral;
6618   }
6619   case Stmt::BinaryOperatorClass: {
6620     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
6621 
6622     // A string literal + an int offset is still a string literal.
6623     if (BinOp->isAdditiveOp()) {
6624       Expr::EvalResult LResult, RResult;
6625 
6626       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
6627       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
6628 
6629       if (LIsInt != RIsInt) {
6630         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
6631 
6632         if (LIsInt) {
6633           if (BinOpKind == BO_Add) {
6634             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
6635             E = BinOp->getRHS();
6636             goto tryAgain;
6637           }
6638         } else {
6639           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
6640           E = BinOp->getLHS();
6641           goto tryAgain;
6642         }
6643       }
6644     }
6645 
6646     return SLCT_NotALiteral;
6647   }
6648   case Stmt::UnaryOperatorClass: {
6649     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
6650     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
6651     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
6652       Expr::EvalResult IndexResult;
6653       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
6654         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
6655                    /*RHS is int*/ true);
6656         E = ASE->getBase();
6657         goto tryAgain;
6658       }
6659     }
6660 
6661     return SLCT_NotALiteral;
6662   }
6663 
6664   default:
6665     return SLCT_NotALiteral;
6666   }
6667 }
6668 
6669 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
6670   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
6671       .Case("scanf", FST_Scanf)
6672       .Cases("printf", "printf0", FST_Printf)
6673       .Cases("NSString", "CFString", FST_NSString)
6674       .Case("strftime", FST_Strftime)
6675       .Case("strfmon", FST_Strfmon)
6676       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
6677       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
6678       .Case("os_trace", FST_OSLog)
6679       .Case("os_log", FST_OSLog)
6680       .Default(FST_Unknown);
6681 }
6682 
6683 /// CheckFormatArguments - Check calls to printf and scanf (and similar
6684 /// functions) for correct use of format strings.
6685 /// Returns true if a format string has been fully checked.
6686 bool Sema::CheckFormatArguments(const FormatAttr *Format,
6687                                 ArrayRef<const Expr *> Args,
6688                                 bool IsCXXMember,
6689                                 VariadicCallType CallType,
6690                                 SourceLocation Loc, SourceRange Range,
6691                                 llvm::SmallBitVector &CheckedVarArgs) {
6692   FormatStringInfo FSI;
6693   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
6694     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
6695                                 FSI.FirstDataArg, GetFormatStringType(Format),
6696                                 CallType, Loc, Range, CheckedVarArgs);
6697   return false;
6698 }
6699 
6700 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
6701                                 bool HasVAListArg, unsigned format_idx,
6702                                 unsigned firstDataArg, FormatStringType Type,
6703                                 VariadicCallType CallType,
6704                                 SourceLocation Loc, SourceRange Range,
6705                                 llvm::SmallBitVector &CheckedVarArgs) {
6706   // CHECK: printf/scanf-like function is called with no format string.
6707   if (format_idx >= Args.size()) {
6708     Diag(Loc, diag::warn_missing_format_string) << Range;
6709     return false;
6710   }
6711 
6712   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
6713 
6714   // CHECK: format string is not a string literal.
6715   //
6716   // Dynamically generated format strings are difficult to
6717   // automatically vet at compile time.  Requiring that format strings
6718   // are string literals: (1) permits the checking of format strings by
6719   // the compiler and thereby (2) can practically remove the source of
6720   // many format string exploits.
6721 
6722   // Format string can be either ObjC string (e.g. @"%d") or
6723   // C string (e.g. "%d")
6724   // ObjC string uses the same format specifiers as C string, so we can use
6725   // the same format string checking logic for both ObjC and C strings.
6726   UncoveredArgHandler UncoveredArg;
6727   StringLiteralCheckType CT =
6728       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
6729                             format_idx, firstDataArg, Type, CallType,
6730                             /*IsFunctionCall*/ true, CheckedVarArgs,
6731                             UncoveredArg,
6732                             /*no string offset*/ llvm::APSInt(64, false) = 0);
6733 
6734   // Generate a diagnostic where an uncovered argument is detected.
6735   if (UncoveredArg.hasUncoveredArg()) {
6736     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
6737     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
6738     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
6739   }
6740 
6741   if (CT != SLCT_NotALiteral)
6742     // Literal format string found, check done!
6743     return CT == SLCT_CheckedLiteral;
6744 
6745   // Strftime is particular as it always uses a single 'time' argument,
6746   // so it is safe to pass a non-literal string.
6747   if (Type == FST_Strftime)
6748     return false;
6749 
6750   // Do not emit diag when the string param is a macro expansion and the
6751   // format is either NSString or CFString. This is a hack to prevent
6752   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
6753   // which are usually used in place of NS and CF string literals.
6754   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
6755   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
6756     return false;
6757 
6758   // If there are no arguments specified, warn with -Wformat-security, otherwise
6759   // warn only with -Wformat-nonliteral.
6760   if (Args.size() == firstDataArg) {
6761     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
6762       << OrigFormatExpr->getSourceRange();
6763     switch (Type) {
6764     default:
6765       break;
6766     case FST_Kprintf:
6767     case FST_FreeBSDKPrintf:
6768     case FST_Printf:
6769       Diag(FormatLoc, diag::note_format_security_fixit)
6770         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
6771       break;
6772     case FST_NSString:
6773       Diag(FormatLoc, diag::note_format_security_fixit)
6774         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
6775       break;
6776     }
6777   } else {
6778     Diag(FormatLoc, diag::warn_format_nonliteral)
6779       << OrigFormatExpr->getSourceRange();
6780   }
6781   return false;
6782 }
6783 
6784 namespace {
6785 
6786 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
6787 protected:
6788   Sema &S;
6789   const FormatStringLiteral *FExpr;
6790   const Expr *OrigFormatExpr;
6791   const Sema::FormatStringType FSType;
6792   const unsigned FirstDataArg;
6793   const unsigned NumDataArgs;
6794   const char *Beg; // Start of format string.
6795   const bool HasVAListArg;
6796   ArrayRef<const Expr *> Args;
6797   unsigned FormatIdx;
6798   llvm::SmallBitVector CoveredArgs;
6799   bool usesPositionalArgs = false;
6800   bool atFirstArg = true;
6801   bool inFunctionCall;
6802   Sema::VariadicCallType CallType;
6803   llvm::SmallBitVector &CheckedVarArgs;
6804   UncoveredArgHandler &UncoveredArg;
6805 
6806 public:
6807   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
6808                      const Expr *origFormatExpr,
6809                      const Sema::FormatStringType type, unsigned firstDataArg,
6810                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
6811                      ArrayRef<const Expr *> Args, unsigned formatIdx,
6812                      bool inFunctionCall, Sema::VariadicCallType callType,
6813                      llvm::SmallBitVector &CheckedVarArgs,
6814                      UncoveredArgHandler &UncoveredArg)
6815       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
6816         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
6817         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
6818         inFunctionCall(inFunctionCall), CallType(callType),
6819         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
6820     CoveredArgs.resize(numDataArgs);
6821     CoveredArgs.reset();
6822   }
6823 
6824   void DoneProcessing();
6825 
6826   void HandleIncompleteSpecifier(const char *startSpecifier,
6827                                  unsigned specifierLen) override;
6828 
6829   void HandleInvalidLengthModifier(
6830                            const analyze_format_string::FormatSpecifier &FS,
6831                            const analyze_format_string::ConversionSpecifier &CS,
6832                            const char *startSpecifier, unsigned specifierLen,
6833                            unsigned DiagID);
6834 
6835   void HandleNonStandardLengthModifier(
6836                     const analyze_format_string::FormatSpecifier &FS,
6837                     const char *startSpecifier, unsigned specifierLen);
6838 
6839   void HandleNonStandardConversionSpecifier(
6840                     const analyze_format_string::ConversionSpecifier &CS,
6841                     const char *startSpecifier, unsigned specifierLen);
6842 
6843   void HandlePosition(const char *startPos, unsigned posLen) override;
6844 
6845   void HandleInvalidPosition(const char *startSpecifier,
6846                              unsigned specifierLen,
6847                              analyze_format_string::PositionContext p) override;
6848 
6849   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
6850 
6851   void HandleNullChar(const char *nullCharacter) override;
6852 
6853   template <typename Range>
6854   static void
6855   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
6856                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
6857                        bool IsStringLocation, Range StringRange,
6858                        ArrayRef<FixItHint> Fixit = None);
6859 
6860 protected:
6861   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
6862                                         const char *startSpec,
6863                                         unsigned specifierLen,
6864                                         const char *csStart, unsigned csLen);
6865 
6866   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
6867                                          const char *startSpec,
6868                                          unsigned specifierLen);
6869 
6870   SourceRange getFormatStringRange();
6871   CharSourceRange getSpecifierRange(const char *startSpecifier,
6872                                     unsigned specifierLen);
6873   SourceLocation getLocationOfByte(const char *x);
6874 
6875   const Expr *getDataArg(unsigned i) const;
6876 
6877   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
6878                     const analyze_format_string::ConversionSpecifier &CS,
6879                     const char *startSpecifier, unsigned specifierLen,
6880                     unsigned argIndex);
6881 
6882   template <typename Range>
6883   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
6884                             bool IsStringLocation, Range StringRange,
6885                             ArrayRef<FixItHint> Fixit = None);
6886 };
6887 
6888 } // namespace
6889 
6890 SourceRange CheckFormatHandler::getFormatStringRange() {
6891   return OrigFormatExpr->getSourceRange();
6892 }
6893 
6894 CharSourceRange CheckFormatHandler::
6895 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
6896   SourceLocation Start = getLocationOfByte(startSpecifier);
6897   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
6898 
6899   // Advance the end SourceLocation by one due to half-open ranges.
6900   End = End.getLocWithOffset(1);
6901 
6902   return CharSourceRange::getCharRange(Start, End);
6903 }
6904 
6905 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
6906   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
6907                                   S.getLangOpts(), S.Context.getTargetInfo());
6908 }
6909 
6910 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
6911                                                    unsigned specifierLen){
6912   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
6913                        getLocationOfByte(startSpecifier),
6914                        /*IsStringLocation*/true,
6915                        getSpecifierRange(startSpecifier, specifierLen));
6916 }
6917 
6918 void CheckFormatHandler::HandleInvalidLengthModifier(
6919     const analyze_format_string::FormatSpecifier &FS,
6920     const analyze_format_string::ConversionSpecifier &CS,
6921     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
6922   using namespace analyze_format_string;
6923 
6924   const LengthModifier &LM = FS.getLengthModifier();
6925   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6926 
6927   // See if we know how to fix this length modifier.
6928   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6929   if (FixedLM) {
6930     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6931                          getLocationOfByte(LM.getStart()),
6932                          /*IsStringLocation*/true,
6933                          getSpecifierRange(startSpecifier, specifierLen));
6934 
6935     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6936       << FixedLM->toString()
6937       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6938 
6939   } else {
6940     FixItHint Hint;
6941     if (DiagID == diag::warn_format_nonsensical_length)
6942       Hint = FixItHint::CreateRemoval(LMRange);
6943 
6944     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
6945                          getLocationOfByte(LM.getStart()),
6946                          /*IsStringLocation*/true,
6947                          getSpecifierRange(startSpecifier, specifierLen),
6948                          Hint);
6949   }
6950 }
6951 
6952 void CheckFormatHandler::HandleNonStandardLengthModifier(
6953     const analyze_format_string::FormatSpecifier &FS,
6954     const char *startSpecifier, unsigned specifierLen) {
6955   using namespace analyze_format_string;
6956 
6957   const LengthModifier &LM = FS.getLengthModifier();
6958   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
6959 
6960   // See if we know how to fix this length modifier.
6961   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
6962   if (FixedLM) {
6963     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6964                            << LM.toString() << 0,
6965                          getLocationOfByte(LM.getStart()),
6966                          /*IsStringLocation*/true,
6967                          getSpecifierRange(startSpecifier, specifierLen));
6968 
6969     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
6970       << FixedLM->toString()
6971       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
6972 
6973   } else {
6974     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6975                            << LM.toString() << 0,
6976                          getLocationOfByte(LM.getStart()),
6977                          /*IsStringLocation*/true,
6978                          getSpecifierRange(startSpecifier, specifierLen));
6979   }
6980 }
6981 
6982 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
6983     const analyze_format_string::ConversionSpecifier &CS,
6984     const char *startSpecifier, unsigned specifierLen) {
6985   using namespace analyze_format_string;
6986 
6987   // See if we know how to fix this conversion specifier.
6988   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
6989   if (FixedCS) {
6990     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
6991                           << CS.toString() << /*conversion specifier*/1,
6992                          getLocationOfByte(CS.getStart()),
6993                          /*IsStringLocation*/true,
6994                          getSpecifierRange(startSpecifier, specifierLen));
6995 
6996     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
6997     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
6998       << FixedCS->toString()
6999       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7000   } else {
7001     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7002                           << CS.toString() << /*conversion specifier*/1,
7003                          getLocationOfByte(CS.getStart()),
7004                          /*IsStringLocation*/true,
7005                          getSpecifierRange(startSpecifier, specifierLen));
7006   }
7007 }
7008 
7009 void CheckFormatHandler::HandlePosition(const char *startPos,
7010                                         unsigned posLen) {
7011   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7012                                getLocationOfByte(startPos),
7013                                /*IsStringLocation*/true,
7014                                getSpecifierRange(startPos, posLen));
7015 }
7016 
7017 void
7018 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7019                                      analyze_format_string::PositionContext p) {
7020   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7021                          << (unsigned) p,
7022                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7023                        getSpecifierRange(startPos, posLen));
7024 }
7025 
7026 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7027                                             unsigned posLen) {
7028   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7029                                getLocationOfByte(startPos),
7030                                /*IsStringLocation*/true,
7031                                getSpecifierRange(startPos, posLen));
7032 }
7033 
7034 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7035   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7036     // The presence of a null character is likely an error.
7037     EmitFormatDiagnostic(
7038       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7039       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7040       getFormatStringRange());
7041   }
7042 }
7043 
7044 // Note that this may return NULL if there was an error parsing or building
7045 // one of the argument expressions.
7046 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7047   return Args[FirstDataArg + i];
7048 }
7049 
7050 void CheckFormatHandler::DoneProcessing() {
7051   // Does the number of data arguments exceed the number of
7052   // format conversions in the format string?
7053   if (!HasVAListArg) {
7054       // Find any arguments that weren't covered.
7055     CoveredArgs.flip();
7056     signed notCoveredArg = CoveredArgs.find_first();
7057     if (notCoveredArg >= 0) {
7058       assert((unsigned)notCoveredArg < NumDataArgs);
7059       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7060     } else {
7061       UncoveredArg.setAllCovered();
7062     }
7063   }
7064 }
7065 
7066 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7067                                    const Expr *ArgExpr) {
7068   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7069          "Invalid state");
7070 
7071   if (!ArgExpr)
7072     return;
7073 
7074   SourceLocation Loc = ArgExpr->getBeginLoc();
7075 
7076   if (S.getSourceManager().isInSystemMacro(Loc))
7077     return;
7078 
7079   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7080   for (auto E : DiagnosticExprs)
7081     PDiag << E->getSourceRange();
7082 
7083   CheckFormatHandler::EmitFormatDiagnostic(
7084                                   S, IsFunctionCall, DiagnosticExprs[0],
7085                                   PDiag, Loc, /*IsStringLocation*/false,
7086                                   DiagnosticExprs[0]->getSourceRange());
7087 }
7088 
7089 bool
7090 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7091                                                      SourceLocation Loc,
7092                                                      const char *startSpec,
7093                                                      unsigned specifierLen,
7094                                                      const char *csStart,
7095                                                      unsigned csLen) {
7096   bool keepGoing = true;
7097   if (argIndex < NumDataArgs) {
7098     // Consider the argument coverered, even though the specifier doesn't
7099     // make sense.
7100     CoveredArgs.set(argIndex);
7101   }
7102   else {
7103     // If argIndex exceeds the number of data arguments we
7104     // don't issue a warning because that is just a cascade of warnings (and
7105     // they may have intended '%%' anyway). We don't want to continue processing
7106     // the format string after this point, however, as we will like just get
7107     // gibberish when trying to match arguments.
7108     keepGoing = false;
7109   }
7110 
7111   StringRef Specifier(csStart, csLen);
7112 
7113   // If the specifier in non-printable, it could be the first byte of a UTF-8
7114   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7115   // hex value.
7116   std::string CodePointStr;
7117   if (!llvm::sys::locale::isPrint(*csStart)) {
7118     llvm::UTF32 CodePoint;
7119     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7120     const llvm::UTF8 *E =
7121         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7122     llvm::ConversionResult Result =
7123         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7124 
7125     if (Result != llvm::conversionOK) {
7126       unsigned char FirstChar = *csStart;
7127       CodePoint = (llvm::UTF32)FirstChar;
7128     }
7129 
7130     llvm::raw_string_ostream OS(CodePointStr);
7131     if (CodePoint < 256)
7132       OS << "\\x" << llvm::format("%02x", CodePoint);
7133     else if (CodePoint <= 0xFFFF)
7134       OS << "\\u" << llvm::format("%04x", CodePoint);
7135     else
7136       OS << "\\U" << llvm::format("%08x", CodePoint);
7137     OS.flush();
7138     Specifier = CodePointStr;
7139   }
7140 
7141   EmitFormatDiagnostic(
7142       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7143       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7144 
7145   return keepGoing;
7146 }
7147 
7148 void
7149 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7150                                                       const char *startSpec,
7151                                                       unsigned specifierLen) {
7152   EmitFormatDiagnostic(
7153     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7154     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7155 }
7156 
7157 bool
7158 CheckFormatHandler::CheckNumArgs(
7159   const analyze_format_string::FormatSpecifier &FS,
7160   const analyze_format_string::ConversionSpecifier &CS,
7161   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7162 
7163   if (argIndex >= NumDataArgs) {
7164     PartialDiagnostic PDiag = FS.usesPositionalArg()
7165       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7166            << (argIndex+1) << NumDataArgs)
7167       : S.PDiag(diag::warn_printf_insufficient_data_args);
7168     EmitFormatDiagnostic(
7169       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7170       getSpecifierRange(startSpecifier, specifierLen));
7171 
7172     // Since more arguments than conversion tokens are given, by extension
7173     // all arguments are covered, so mark this as so.
7174     UncoveredArg.setAllCovered();
7175     return false;
7176   }
7177   return true;
7178 }
7179 
7180 template<typename Range>
7181 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7182                                               SourceLocation Loc,
7183                                               bool IsStringLocation,
7184                                               Range StringRange,
7185                                               ArrayRef<FixItHint> FixIt) {
7186   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7187                        Loc, IsStringLocation, StringRange, FixIt);
7188 }
7189 
7190 /// If the format string is not within the function call, emit a note
7191 /// so that the function call and string are in diagnostic messages.
7192 ///
7193 /// \param InFunctionCall if true, the format string is within the function
7194 /// call and only one diagnostic message will be produced.  Otherwise, an
7195 /// extra note will be emitted pointing to location of the format string.
7196 ///
7197 /// \param ArgumentExpr the expression that is passed as the format string
7198 /// argument in the function call.  Used for getting locations when two
7199 /// diagnostics are emitted.
7200 ///
7201 /// \param PDiag the callee should already have provided any strings for the
7202 /// diagnostic message.  This function only adds locations and fixits
7203 /// to diagnostics.
7204 ///
7205 /// \param Loc primary location for diagnostic.  If two diagnostics are
7206 /// required, one will be at Loc and a new SourceLocation will be created for
7207 /// the other one.
7208 ///
7209 /// \param IsStringLocation if true, Loc points to the format string should be
7210 /// used for the note.  Otherwise, Loc points to the argument list and will
7211 /// be used with PDiag.
7212 ///
7213 /// \param StringRange some or all of the string to highlight.  This is
7214 /// templated so it can accept either a CharSourceRange or a SourceRange.
7215 ///
7216 /// \param FixIt optional fix it hint for the format string.
7217 template <typename Range>
7218 void CheckFormatHandler::EmitFormatDiagnostic(
7219     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7220     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7221     Range StringRange, ArrayRef<FixItHint> FixIt) {
7222   if (InFunctionCall) {
7223     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7224     D << StringRange;
7225     D << FixIt;
7226   } else {
7227     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7228       << ArgumentExpr->getSourceRange();
7229 
7230     const Sema::SemaDiagnosticBuilder &Note =
7231       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7232              diag::note_format_string_defined);
7233 
7234     Note << StringRange;
7235     Note << FixIt;
7236   }
7237 }
7238 
7239 //===--- CHECK: Printf format string checking ------------------------------===//
7240 
7241 namespace {
7242 
7243 class CheckPrintfHandler : public CheckFormatHandler {
7244 public:
7245   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7246                      const Expr *origFormatExpr,
7247                      const Sema::FormatStringType type, unsigned firstDataArg,
7248                      unsigned numDataArgs, bool isObjC, const char *beg,
7249                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7250                      unsigned formatIdx, bool inFunctionCall,
7251                      Sema::VariadicCallType CallType,
7252                      llvm::SmallBitVector &CheckedVarArgs,
7253                      UncoveredArgHandler &UncoveredArg)
7254       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7255                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7256                            inFunctionCall, CallType, CheckedVarArgs,
7257                            UncoveredArg) {}
7258 
7259   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7260 
7261   /// Returns true if '%@' specifiers are allowed in the format string.
7262   bool allowsObjCArg() const {
7263     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7264            FSType == Sema::FST_OSTrace;
7265   }
7266 
7267   bool HandleInvalidPrintfConversionSpecifier(
7268                                       const analyze_printf::PrintfSpecifier &FS,
7269                                       const char *startSpecifier,
7270                                       unsigned specifierLen) override;
7271 
7272   void handleInvalidMaskType(StringRef MaskType) override;
7273 
7274   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7275                              const char *startSpecifier,
7276                              unsigned specifierLen) override;
7277   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7278                        const char *StartSpecifier,
7279                        unsigned SpecifierLen,
7280                        const Expr *E);
7281 
7282   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7283                     const char *startSpecifier, unsigned specifierLen);
7284   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7285                            const analyze_printf::OptionalAmount &Amt,
7286                            unsigned type,
7287                            const char *startSpecifier, unsigned specifierLen);
7288   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7289                   const analyze_printf::OptionalFlag &flag,
7290                   const char *startSpecifier, unsigned specifierLen);
7291   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7292                          const analyze_printf::OptionalFlag &ignoredFlag,
7293                          const analyze_printf::OptionalFlag &flag,
7294                          const char *startSpecifier, unsigned specifierLen);
7295   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7296                            const Expr *E);
7297 
7298   void HandleEmptyObjCModifierFlag(const char *startFlag,
7299                                    unsigned flagLen) override;
7300 
7301   void HandleInvalidObjCModifierFlag(const char *startFlag,
7302                                             unsigned flagLen) override;
7303 
7304   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7305                                            const char *flagsEnd,
7306                                            const char *conversionPosition)
7307                                              override;
7308 };
7309 
7310 } // namespace
7311 
7312 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7313                                       const analyze_printf::PrintfSpecifier &FS,
7314                                       const char *startSpecifier,
7315                                       unsigned specifierLen) {
7316   const analyze_printf::PrintfConversionSpecifier &CS =
7317     FS.getConversionSpecifier();
7318 
7319   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
7320                                           getLocationOfByte(CS.getStart()),
7321                                           startSpecifier, specifierLen,
7322                                           CS.getStart(), CS.getLength());
7323 }
7324 
7325 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
7326   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
7327 }
7328 
7329 bool CheckPrintfHandler::HandleAmount(
7330                                const analyze_format_string::OptionalAmount &Amt,
7331                                unsigned k, const char *startSpecifier,
7332                                unsigned specifierLen) {
7333   if (Amt.hasDataArgument()) {
7334     if (!HasVAListArg) {
7335       unsigned argIndex = Amt.getArgIndex();
7336       if (argIndex >= NumDataArgs) {
7337         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
7338                                << k,
7339                              getLocationOfByte(Amt.getStart()),
7340                              /*IsStringLocation*/true,
7341                              getSpecifierRange(startSpecifier, specifierLen));
7342         // Don't do any more checking.  We will just emit
7343         // spurious errors.
7344         return false;
7345       }
7346 
7347       // Type check the data argument.  It should be an 'int'.
7348       // Although not in conformance with C99, we also allow the argument to be
7349       // an 'unsigned int' as that is a reasonably safe case.  GCC also
7350       // doesn't emit a warning for that case.
7351       CoveredArgs.set(argIndex);
7352       const Expr *Arg = getDataArg(argIndex);
7353       if (!Arg)
7354         return false;
7355 
7356       QualType T = Arg->getType();
7357 
7358       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
7359       assert(AT.isValid());
7360 
7361       if (!AT.matchesType(S.Context, T)) {
7362         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
7363                                << k << AT.getRepresentativeTypeName(S.Context)
7364                                << T << Arg->getSourceRange(),
7365                              getLocationOfByte(Amt.getStart()),
7366                              /*IsStringLocation*/true,
7367                              getSpecifierRange(startSpecifier, specifierLen));
7368         // Don't do any more checking.  We will just emit
7369         // spurious errors.
7370         return false;
7371       }
7372     }
7373   }
7374   return true;
7375 }
7376 
7377 void CheckPrintfHandler::HandleInvalidAmount(
7378                                       const analyze_printf::PrintfSpecifier &FS,
7379                                       const analyze_printf::OptionalAmount &Amt,
7380                                       unsigned type,
7381                                       const char *startSpecifier,
7382                                       unsigned specifierLen) {
7383   const analyze_printf::PrintfConversionSpecifier &CS =
7384     FS.getConversionSpecifier();
7385 
7386   FixItHint fixit =
7387     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
7388       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
7389                                  Amt.getConstantLength()))
7390       : FixItHint();
7391 
7392   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
7393                          << type << CS.toString(),
7394                        getLocationOfByte(Amt.getStart()),
7395                        /*IsStringLocation*/true,
7396                        getSpecifierRange(startSpecifier, specifierLen),
7397                        fixit);
7398 }
7399 
7400 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7401                                     const analyze_printf::OptionalFlag &flag,
7402                                     const char *startSpecifier,
7403                                     unsigned specifierLen) {
7404   // Warn about pointless flag with a fixit removal.
7405   const analyze_printf::PrintfConversionSpecifier &CS =
7406     FS.getConversionSpecifier();
7407   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
7408                          << flag.toString() << CS.toString(),
7409                        getLocationOfByte(flag.getPosition()),
7410                        /*IsStringLocation*/true,
7411                        getSpecifierRange(startSpecifier, specifierLen),
7412                        FixItHint::CreateRemoval(
7413                          getSpecifierRange(flag.getPosition(), 1)));
7414 }
7415 
7416 void CheckPrintfHandler::HandleIgnoredFlag(
7417                                 const analyze_printf::PrintfSpecifier &FS,
7418                                 const analyze_printf::OptionalFlag &ignoredFlag,
7419                                 const analyze_printf::OptionalFlag &flag,
7420                                 const char *startSpecifier,
7421                                 unsigned specifierLen) {
7422   // Warn about ignored flag with a fixit removal.
7423   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
7424                          << ignoredFlag.toString() << flag.toString(),
7425                        getLocationOfByte(ignoredFlag.getPosition()),
7426                        /*IsStringLocation*/true,
7427                        getSpecifierRange(startSpecifier, specifierLen),
7428                        FixItHint::CreateRemoval(
7429                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
7430 }
7431 
7432 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
7433                                                      unsigned flagLen) {
7434   // Warn about an empty flag.
7435   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
7436                        getLocationOfByte(startFlag),
7437                        /*IsStringLocation*/true,
7438                        getSpecifierRange(startFlag, flagLen));
7439 }
7440 
7441 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
7442                                                        unsigned flagLen) {
7443   // Warn about an invalid flag.
7444   auto Range = getSpecifierRange(startFlag, flagLen);
7445   StringRef flag(startFlag, flagLen);
7446   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
7447                       getLocationOfByte(startFlag),
7448                       /*IsStringLocation*/true,
7449                       Range, FixItHint::CreateRemoval(Range));
7450 }
7451 
7452 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
7453     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
7454     // Warn about using '[...]' without a '@' conversion.
7455     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
7456     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
7457     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
7458                          getLocationOfByte(conversionPosition),
7459                          /*IsStringLocation*/true,
7460                          Range, FixItHint::CreateRemoval(Range));
7461 }
7462 
7463 // Determines if the specified is a C++ class or struct containing
7464 // a member with the specified name and kind (e.g. a CXXMethodDecl named
7465 // "c_str()").
7466 template<typename MemberKind>
7467 static llvm::SmallPtrSet<MemberKind*, 1>
7468 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
7469   const RecordType *RT = Ty->getAs<RecordType>();
7470   llvm::SmallPtrSet<MemberKind*, 1> Results;
7471 
7472   if (!RT)
7473     return Results;
7474   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
7475   if (!RD || !RD->getDefinition())
7476     return Results;
7477 
7478   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
7479                  Sema::LookupMemberName);
7480   R.suppressDiagnostics();
7481 
7482   // We just need to include all members of the right kind turned up by the
7483   // filter, at this point.
7484   if (S.LookupQualifiedName(R, RT->getDecl()))
7485     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
7486       NamedDecl *decl = (*I)->getUnderlyingDecl();
7487       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
7488         Results.insert(FK);
7489     }
7490   return Results;
7491 }
7492 
7493 /// Check if we could call '.c_str()' on an object.
7494 ///
7495 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
7496 /// allow the call, or if it would be ambiguous).
7497 bool Sema::hasCStrMethod(const Expr *E) {
7498   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7499 
7500   MethodSet Results =
7501       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
7502   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7503        MI != ME; ++MI)
7504     if ((*MI)->getMinRequiredArguments() == 0)
7505       return true;
7506   return false;
7507 }
7508 
7509 // Check if a (w)string was passed when a (w)char* was needed, and offer a
7510 // better diagnostic if so. AT is assumed to be valid.
7511 // Returns true when a c_str() conversion method is found.
7512 bool CheckPrintfHandler::checkForCStrMembers(
7513     const analyze_printf::ArgType &AT, const Expr *E) {
7514   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
7515 
7516   MethodSet Results =
7517       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
7518 
7519   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
7520        MI != ME; ++MI) {
7521     const CXXMethodDecl *Method = *MI;
7522     if (Method->getMinRequiredArguments() == 0 &&
7523         AT.matchesType(S.Context, Method->getReturnType())) {
7524       // FIXME: Suggest parens if the expression needs them.
7525       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
7526       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
7527           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
7528       return true;
7529     }
7530   }
7531 
7532   return false;
7533 }
7534 
7535 bool
7536 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
7537                                             &FS,
7538                                           const char *startSpecifier,
7539                                           unsigned specifierLen) {
7540   using namespace analyze_format_string;
7541   using namespace analyze_printf;
7542 
7543   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
7544 
7545   if (FS.consumesDataArgument()) {
7546     if (atFirstArg) {
7547         atFirstArg = false;
7548         usesPositionalArgs = FS.usesPositionalArg();
7549     }
7550     else if (usesPositionalArgs != FS.usesPositionalArg()) {
7551       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
7552                                         startSpecifier, specifierLen);
7553       return false;
7554     }
7555   }
7556 
7557   // First check if the field width, precision, and conversion specifier
7558   // have matching data arguments.
7559   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
7560                     startSpecifier, specifierLen)) {
7561     return false;
7562   }
7563 
7564   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
7565                     startSpecifier, specifierLen)) {
7566     return false;
7567   }
7568 
7569   if (!CS.consumesDataArgument()) {
7570     // FIXME: Technically specifying a precision or field width here
7571     // makes no sense.  Worth issuing a warning at some point.
7572     return true;
7573   }
7574 
7575   // Consume the argument.
7576   unsigned argIndex = FS.getArgIndex();
7577   if (argIndex < NumDataArgs) {
7578     // The check to see if the argIndex is valid will come later.
7579     // We set the bit here because we may exit early from this
7580     // function if we encounter some other error.
7581     CoveredArgs.set(argIndex);
7582   }
7583 
7584   // FreeBSD kernel extensions.
7585   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
7586       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
7587     // We need at least two arguments.
7588     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
7589       return false;
7590 
7591     // Claim the second argument.
7592     CoveredArgs.set(argIndex + 1);
7593 
7594     // Type check the first argument (int for %b, pointer for %D)
7595     const Expr *Ex = getDataArg(argIndex);
7596     const analyze_printf::ArgType &AT =
7597       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
7598         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
7599     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
7600       EmitFormatDiagnostic(
7601           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7602               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
7603               << false << Ex->getSourceRange(),
7604           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7605           getSpecifierRange(startSpecifier, specifierLen));
7606 
7607     // Type check the second argument (char * for both %b and %D)
7608     Ex = getDataArg(argIndex + 1);
7609     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
7610     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
7611       EmitFormatDiagnostic(
7612           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
7613               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
7614               << false << Ex->getSourceRange(),
7615           Ex->getBeginLoc(), /*IsStringLocation*/ false,
7616           getSpecifierRange(startSpecifier, specifierLen));
7617 
7618      return true;
7619   }
7620 
7621   // Check for using an Objective-C specific conversion specifier
7622   // in a non-ObjC literal.
7623   if (!allowsObjCArg() && CS.isObjCArg()) {
7624     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7625                                                   specifierLen);
7626   }
7627 
7628   // %P can only be used with os_log.
7629   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
7630     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7631                                                   specifierLen);
7632   }
7633 
7634   // %n is not allowed with os_log.
7635   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
7636     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
7637                          getLocationOfByte(CS.getStart()),
7638                          /*IsStringLocation*/ false,
7639                          getSpecifierRange(startSpecifier, specifierLen));
7640 
7641     return true;
7642   }
7643 
7644   // Only scalars are allowed for os_trace.
7645   if (FSType == Sema::FST_OSTrace &&
7646       (CS.getKind() == ConversionSpecifier::PArg ||
7647        CS.getKind() == ConversionSpecifier::sArg ||
7648        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
7649     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
7650                                                   specifierLen);
7651   }
7652 
7653   // Check for use of public/private annotation outside of os_log().
7654   if (FSType != Sema::FST_OSLog) {
7655     if (FS.isPublic().isSet()) {
7656       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7657                                << "public",
7658                            getLocationOfByte(FS.isPublic().getPosition()),
7659                            /*IsStringLocation*/ false,
7660                            getSpecifierRange(startSpecifier, specifierLen));
7661     }
7662     if (FS.isPrivate().isSet()) {
7663       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
7664                                << "private",
7665                            getLocationOfByte(FS.isPrivate().getPosition()),
7666                            /*IsStringLocation*/ false,
7667                            getSpecifierRange(startSpecifier, specifierLen));
7668     }
7669   }
7670 
7671   // Check for invalid use of field width
7672   if (!FS.hasValidFieldWidth()) {
7673     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
7674         startSpecifier, specifierLen);
7675   }
7676 
7677   // Check for invalid use of precision
7678   if (!FS.hasValidPrecision()) {
7679     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
7680         startSpecifier, specifierLen);
7681   }
7682 
7683   // Precision is mandatory for %P specifier.
7684   if (CS.getKind() == ConversionSpecifier::PArg &&
7685       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
7686     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
7687                          getLocationOfByte(startSpecifier),
7688                          /*IsStringLocation*/ false,
7689                          getSpecifierRange(startSpecifier, specifierLen));
7690   }
7691 
7692   // Check each flag does not conflict with any other component.
7693   if (!FS.hasValidThousandsGroupingPrefix())
7694     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
7695   if (!FS.hasValidLeadingZeros())
7696     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
7697   if (!FS.hasValidPlusPrefix())
7698     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
7699   if (!FS.hasValidSpacePrefix())
7700     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
7701   if (!FS.hasValidAlternativeForm())
7702     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
7703   if (!FS.hasValidLeftJustified())
7704     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
7705 
7706   // Check that flags are not ignored by another flag
7707   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
7708     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
7709         startSpecifier, specifierLen);
7710   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
7711     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
7712             startSpecifier, specifierLen);
7713 
7714   // Check the length modifier is valid with the given conversion specifier.
7715   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
7716                                  S.getLangOpts()))
7717     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7718                                 diag::warn_format_nonsensical_length);
7719   else if (!FS.hasStandardLengthModifier())
7720     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
7721   else if (!FS.hasStandardLengthConversionCombination())
7722     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
7723                                 diag::warn_format_non_standard_conversion_spec);
7724 
7725   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
7726     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
7727 
7728   // The remaining checks depend on the data arguments.
7729   if (HasVAListArg)
7730     return true;
7731 
7732   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
7733     return false;
7734 
7735   const Expr *Arg = getDataArg(argIndex);
7736   if (!Arg)
7737     return true;
7738 
7739   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
7740 }
7741 
7742 static bool requiresParensToAddCast(const Expr *E) {
7743   // FIXME: We should have a general way to reason about operator
7744   // precedence and whether parens are actually needed here.
7745   // Take care of a few common cases where they aren't.
7746   const Expr *Inside = E->IgnoreImpCasts();
7747   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
7748     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
7749 
7750   switch (Inside->getStmtClass()) {
7751   case Stmt::ArraySubscriptExprClass:
7752   case Stmt::CallExprClass:
7753   case Stmt::CharacterLiteralClass:
7754   case Stmt::CXXBoolLiteralExprClass:
7755   case Stmt::DeclRefExprClass:
7756   case Stmt::FloatingLiteralClass:
7757   case Stmt::IntegerLiteralClass:
7758   case Stmt::MemberExprClass:
7759   case Stmt::ObjCArrayLiteralClass:
7760   case Stmt::ObjCBoolLiteralExprClass:
7761   case Stmt::ObjCBoxedExprClass:
7762   case Stmt::ObjCDictionaryLiteralClass:
7763   case Stmt::ObjCEncodeExprClass:
7764   case Stmt::ObjCIvarRefExprClass:
7765   case Stmt::ObjCMessageExprClass:
7766   case Stmt::ObjCPropertyRefExprClass:
7767   case Stmt::ObjCStringLiteralClass:
7768   case Stmt::ObjCSubscriptRefExprClass:
7769   case Stmt::ParenExprClass:
7770   case Stmt::StringLiteralClass:
7771   case Stmt::UnaryOperatorClass:
7772     return false;
7773   default:
7774     return true;
7775   }
7776 }
7777 
7778 static std::pair<QualType, StringRef>
7779 shouldNotPrintDirectly(const ASTContext &Context,
7780                        QualType IntendedTy,
7781                        const Expr *E) {
7782   // Use a 'while' to peel off layers of typedefs.
7783   QualType TyTy = IntendedTy;
7784   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
7785     StringRef Name = UserTy->getDecl()->getName();
7786     QualType CastTy = llvm::StringSwitch<QualType>(Name)
7787       .Case("CFIndex", Context.getNSIntegerType())
7788       .Case("NSInteger", Context.getNSIntegerType())
7789       .Case("NSUInteger", Context.getNSUIntegerType())
7790       .Case("SInt32", Context.IntTy)
7791       .Case("UInt32", Context.UnsignedIntTy)
7792       .Default(QualType());
7793 
7794     if (!CastTy.isNull())
7795       return std::make_pair(CastTy, Name);
7796 
7797     TyTy = UserTy->desugar();
7798   }
7799 
7800   // Strip parens if necessary.
7801   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
7802     return shouldNotPrintDirectly(Context,
7803                                   PE->getSubExpr()->getType(),
7804                                   PE->getSubExpr());
7805 
7806   // If this is a conditional expression, then its result type is constructed
7807   // via usual arithmetic conversions and thus there might be no necessary
7808   // typedef sugar there.  Recurse to operands to check for NSInteger &
7809   // Co. usage condition.
7810   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
7811     QualType TrueTy, FalseTy;
7812     StringRef TrueName, FalseName;
7813 
7814     std::tie(TrueTy, TrueName) =
7815       shouldNotPrintDirectly(Context,
7816                              CO->getTrueExpr()->getType(),
7817                              CO->getTrueExpr());
7818     std::tie(FalseTy, FalseName) =
7819       shouldNotPrintDirectly(Context,
7820                              CO->getFalseExpr()->getType(),
7821                              CO->getFalseExpr());
7822 
7823     if (TrueTy == FalseTy)
7824       return std::make_pair(TrueTy, TrueName);
7825     else if (TrueTy.isNull())
7826       return std::make_pair(FalseTy, FalseName);
7827     else if (FalseTy.isNull())
7828       return std::make_pair(TrueTy, TrueName);
7829   }
7830 
7831   return std::make_pair(QualType(), StringRef());
7832 }
7833 
7834 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
7835 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
7836 /// type do not count.
7837 static bool
7838 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
7839   QualType From = ICE->getSubExpr()->getType();
7840   QualType To = ICE->getType();
7841   // It's an integer promotion if the destination type is the promoted
7842   // source type.
7843   if (ICE->getCastKind() == CK_IntegralCast &&
7844       From->isPromotableIntegerType() &&
7845       S.Context.getPromotedIntegerType(From) == To)
7846     return true;
7847   // Look through vector types, since we do default argument promotion for
7848   // those in OpenCL.
7849   if (const auto *VecTy = From->getAs<ExtVectorType>())
7850     From = VecTy->getElementType();
7851   if (const auto *VecTy = To->getAs<ExtVectorType>())
7852     To = VecTy->getElementType();
7853   // It's a floating promotion if the source type is a lower rank.
7854   return ICE->getCastKind() == CK_FloatingCast &&
7855          S.Context.getFloatingTypeOrder(From, To) < 0;
7856 }
7857 
7858 bool
7859 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7860                                     const char *StartSpecifier,
7861                                     unsigned SpecifierLen,
7862                                     const Expr *E) {
7863   using namespace analyze_format_string;
7864   using namespace analyze_printf;
7865 
7866   // Now type check the data expression that matches the
7867   // format specifier.
7868   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
7869   if (!AT.isValid())
7870     return true;
7871 
7872   QualType ExprTy = E->getType();
7873   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
7874     ExprTy = TET->getUnderlyingExpr()->getType();
7875   }
7876 
7877   const analyze_printf::ArgType::MatchKind Match =
7878       AT.matchesType(S.Context, ExprTy);
7879   bool Pedantic = Match == analyze_printf::ArgType::NoMatchPedantic;
7880   if (Match == analyze_printf::ArgType::Match)
7881     return true;
7882 
7883   // Look through argument promotions for our error message's reported type.
7884   // This includes the integral and floating promotions, but excludes array
7885   // and function pointer decay (seeing that an argument intended to be a
7886   // string has type 'char [6]' is probably more confusing than 'char *') and
7887   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
7888   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7889     if (isArithmeticArgumentPromotion(S, ICE)) {
7890       E = ICE->getSubExpr();
7891       ExprTy = E->getType();
7892 
7893       // Check if we didn't match because of an implicit cast from a 'char'
7894       // or 'short' to an 'int'.  This is done because printf is a varargs
7895       // function.
7896       if (ICE->getType() == S.Context.IntTy ||
7897           ICE->getType() == S.Context.UnsignedIntTy) {
7898         // All further checking is done on the subexpression.
7899         if (AT.matchesType(S.Context, ExprTy))
7900           return true;
7901       }
7902     }
7903   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
7904     // Special case for 'a', which has type 'int' in C.
7905     // Note, however, that we do /not/ want to treat multibyte constants like
7906     // 'MooV' as characters! This form is deprecated but still exists.
7907     if (ExprTy == S.Context.IntTy)
7908       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
7909         ExprTy = S.Context.CharTy;
7910   }
7911 
7912   // Look through enums to their underlying type.
7913   bool IsEnum = false;
7914   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
7915     ExprTy = EnumTy->getDecl()->getIntegerType();
7916     IsEnum = true;
7917   }
7918 
7919   // %C in an Objective-C context prints a unichar, not a wchar_t.
7920   // If the argument is an integer of some kind, believe the %C and suggest
7921   // a cast instead of changing the conversion specifier.
7922   QualType IntendedTy = ExprTy;
7923   if (isObjCContext() &&
7924       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
7925     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
7926         !ExprTy->isCharType()) {
7927       // 'unichar' is defined as a typedef of unsigned short, but we should
7928       // prefer using the typedef if it is visible.
7929       IntendedTy = S.Context.UnsignedShortTy;
7930 
7931       // While we are here, check if the value is an IntegerLiteral that happens
7932       // to be within the valid range.
7933       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
7934         const llvm::APInt &V = IL->getValue();
7935         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
7936           return true;
7937       }
7938 
7939       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
7940                           Sema::LookupOrdinaryName);
7941       if (S.LookupName(Result, S.getCurScope())) {
7942         NamedDecl *ND = Result.getFoundDecl();
7943         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
7944           if (TD->getUnderlyingType() == IntendedTy)
7945             IntendedTy = S.Context.getTypedefType(TD);
7946       }
7947     }
7948   }
7949 
7950   // Special-case some of Darwin's platform-independence types by suggesting
7951   // casts to primitive types that are known to be large enough.
7952   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
7953   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
7954     QualType CastTy;
7955     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
7956     if (!CastTy.isNull()) {
7957       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
7958       // (long in ASTContext). Only complain to pedants.
7959       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
7960           (AT.isSizeT() || AT.isPtrdiffT()) &&
7961           AT.matchesType(S.Context, CastTy))
7962         Pedantic = true;
7963       IntendedTy = CastTy;
7964       ShouldNotPrintDirectly = true;
7965     }
7966   }
7967 
7968   // We may be able to offer a FixItHint if it is a supported type.
7969   PrintfSpecifier fixedFS = FS;
7970   bool Success =
7971       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
7972 
7973   if (Success) {
7974     // Get the fix string from the fixed format specifier
7975     SmallString<16> buf;
7976     llvm::raw_svector_ostream os(buf);
7977     fixedFS.toString(os);
7978 
7979     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
7980 
7981     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
7982       unsigned Diag =
7983           Pedantic
7984               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
7985               : diag::warn_format_conversion_argument_type_mismatch;
7986       // In this case, the specifier is wrong and should be changed to match
7987       // the argument.
7988       EmitFormatDiagnostic(S.PDiag(Diag)
7989                                << AT.getRepresentativeTypeName(S.Context)
7990                                << IntendedTy << IsEnum << E->getSourceRange(),
7991                            E->getBeginLoc(),
7992                            /*IsStringLocation*/ false, SpecRange,
7993                            FixItHint::CreateReplacement(SpecRange, os.str()));
7994     } else {
7995       // The canonical type for formatting this value is different from the
7996       // actual type of the expression. (This occurs, for example, with Darwin's
7997       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
7998       // should be printed as 'long' for 64-bit compatibility.)
7999       // Rather than emitting a normal format/argument mismatch, we want to
8000       // add a cast to the recommended type (and correct the format string
8001       // if necessary).
8002       SmallString<16> CastBuf;
8003       llvm::raw_svector_ostream CastFix(CastBuf);
8004       CastFix << "(";
8005       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8006       CastFix << ")";
8007 
8008       SmallVector<FixItHint,4> Hints;
8009       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8010         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8011 
8012       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8013         // If there's already a cast present, just replace it.
8014         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8015         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8016 
8017       } else if (!requiresParensToAddCast(E)) {
8018         // If the expression has high enough precedence,
8019         // just write the C-style cast.
8020         Hints.push_back(
8021             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8022       } else {
8023         // Otherwise, add parens around the expression as well as the cast.
8024         CastFix << "(";
8025         Hints.push_back(
8026             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8027 
8028         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8029         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8030       }
8031 
8032       if (ShouldNotPrintDirectly) {
8033         // The expression has a type that should not be printed directly.
8034         // We extract the name from the typedef because we don't want to show
8035         // the underlying type in the diagnostic.
8036         StringRef Name;
8037         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8038           Name = TypedefTy->getDecl()->getName();
8039         else
8040           Name = CastTyName;
8041         unsigned Diag = Pedantic
8042                             ? diag::warn_format_argument_needs_cast_pedantic
8043                             : diag::warn_format_argument_needs_cast;
8044         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8045                                            << E->getSourceRange(),
8046                              E->getBeginLoc(), /*IsStringLocation=*/false,
8047                              SpecRange, Hints);
8048       } else {
8049         // In this case, the expression could be printed using a different
8050         // specifier, but we've decided that the specifier is probably correct
8051         // and we should cast instead. Just use the normal warning message.
8052         EmitFormatDiagnostic(
8053             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8054                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8055                 << E->getSourceRange(),
8056             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8057       }
8058     }
8059   } else {
8060     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8061                                                    SpecifierLen);
8062     // Since the warning for passing non-POD types to variadic functions
8063     // was deferred until now, we emit a warning for non-POD
8064     // arguments here.
8065     switch (S.isValidVarArgType(ExprTy)) {
8066     case Sema::VAK_Valid:
8067     case Sema::VAK_ValidInCXX11: {
8068       unsigned Diag =
8069           Pedantic
8070               ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8071               : diag::warn_format_conversion_argument_type_mismatch;
8072 
8073       EmitFormatDiagnostic(
8074           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8075                         << IsEnum << CSR << E->getSourceRange(),
8076           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8077       break;
8078     }
8079     case Sema::VAK_Undefined:
8080     case Sema::VAK_MSVCUndefined:
8081       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8082                                << S.getLangOpts().CPlusPlus11 << ExprTy
8083                                << CallType
8084                                << AT.getRepresentativeTypeName(S.Context) << CSR
8085                                << E->getSourceRange(),
8086                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8087       checkForCStrMembers(AT, E);
8088       break;
8089 
8090     case Sema::VAK_Invalid:
8091       if (ExprTy->isObjCObjectType())
8092         EmitFormatDiagnostic(
8093             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8094                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8095                 << AT.getRepresentativeTypeName(S.Context) << CSR
8096                 << E->getSourceRange(),
8097             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8098       else
8099         // FIXME: If this is an initializer list, suggest removing the braces
8100         // or inserting a cast to the target type.
8101         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8102             << isa<InitListExpr>(E) << ExprTy << CallType
8103             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8104       break;
8105     }
8106 
8107     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8108            "format string specifier index out of range");
8109     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8110   }
8111 
8112   return true;
8113 }
8114 
8115 //===--- CHECK: Scanf format string checking ------------------------------===//
8116 
8117 namespace {
8118 
8119 class CheckScanfHandler : public CheckFormatHandler {
8120 public:
8121   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8122                     const Expr *origFormatExpr, Sema::FormatStringType type,
8123                     unsigned firstDataArg, unsigned numDataArgs,
8124                     const char *beg, bool hasVAListArg,
8125                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8126                     bool inFunctionCall, Sema::VariadicCallType CallType,
8127                     llvm::SmallBitVector &CheckedVarArgs,
8128                     UncoveredArgHandler &UncoveredArg)
8129       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8130                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8131                            inFunctionCall, CallType, CheckedVarArgs,
8132                            UncoveredArg) {}
8133 
8134   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8135                             const char *startSpecifier,
8136                             unsigned specifierLen) override;
8137 
8138   bool HandleInvalidScanfConversionSpecifier(
8139           const analyze_scanf::ScanfSpecifier &FS,
8140           const char *startSpecifier,
8141           unsigned specifierLen) override;
8142 
8143   void HandleIncompleteScanList(const char *start, const char *end) override;
8144 };
8145 
8146 } // namespace
8147 
8148 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8149                                                  const char *end) {
8150   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8151                        getLocationOfByte(end), /*IsStringLocation*/true,
8152                        getSpecifierRange(start, end - start));
8153 }
8154 
8155 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8156                                         const analyze_scanf::ScanfSpecifier &FS,
8157                                         const char *startSpecifier,
8158                                         unsigned specifierLen) {
8159   const analyze_scanf::ScanfConversionSpecifier &CS =
8160     FS.getConversionSpecifier();
8161 
8162   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8163                                           getLocationOfByte(CS.getStart()),
8164                                           startSpecifier, specifierLen,
8165                                           CS.getStart(), CS.getLength());
8166 }
8167 
8168 bool CheckScanfHandler::HandleScanfSpecifier(
8169                                        const analyze_scanf::ScanfSpecifier &FS,
8170                                        const char *startSpecifier,
8171                                        unsigned specifierLen) {
8172   using namespace analyze_scanf;
8173   using namespace analyze_format_string;
8174 
8175   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8176 
8177   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8178   // be used to decide if we are using positional arguments consistently.
8179   if (FS.consumesDataArgument()) {
8180     if (atFirstArg) {
8181       atFirstArg = false;
8182       usesPositionalArgs = FS.usesPositionalArg();
8183     }
8184     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8185       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8186                                         startSpecifier, specifierLen);
8187       return false;
8188     }
8189   }
8190 
8191   // Check if the field with is non-zero.
8192   const OptionalAmount &Amt = FS.getFieldWidth();
8193   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8194     if (Amt.getConstantAmount() == 0) {
8195       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8196                                                    Amt.getConstantLength());
8197       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8198                            getLocationOfByte(Amt.getStart()),
8199                            /*IsStringLocation*/true, R,
8200                            FixItHint::CreateRemoval(R));
8201     }
8202   }
8203 
8204   if (!FS.consumesDataArgument()) {
8205     // FIXME: Technically specifying a precision or field width here
8206     // makes no sense.  Worth issuing a warning at some point.
8207     return true;
8208   }
8209 
8210   // Consume the argument.
8211   unsigned argIndex = FS.getArgIndex();
8212   if (argIndex < NumDataArgs) {
8213       // The check to see if the argIndex is valid will come later.
8214       // We set the bit here because we may exit early from this
8215       // function if we encounter some other error.
8216     CoveredArgs.set(argIndex);
8217   }
8218 
8219   // Check the length modifier is valid with the given conversion specifier.
8220   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8221                                  S.getLangOpts()))
8222     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8223                                 diag::warn_format_nonsensical_length);
8224   else if (!FS.hasStandardLengthModifier())
8225     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8226   else if (!FS.hasStandardLengthConversionCombination())
8227     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8228                                 diag::warn_format_non_standard_conversion_spec);
8229 
8230   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8231     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8232 
8233   // The remaining checks depend on the data arguments.
8234   if (HasVAListArg)
8235     return true;
8236 
8237   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8238     return false;
8239 
8240   // Check that the argument type matches the format specifier.
8241   const Expr *Ex = getDataArg(argIndex);
8242   if (!Ex)
8243     return true;
8244 
8245   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8246 
8247   if (!AT.isValid()) {
8248     return true;
8249   }
8250 
8251   analyze_format_string::ArgType::MatchKind Match =
8252       AT.matchesType(S.Context, Ex->getType());
8253   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8254   if (Match == analyze_format_string::ArgType::Match)
8255     return true;
8256 
8257   ScanfSpecifier fixedFS = FS;
8258   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8259                                  S.getLangOpts(), S.Context);
8260 
8261   unsigned Diag =
8262       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8263                : diag::warn_format_conversion_argument_type_mismatch;
8264 
8265   if (Success) {
8266     // Get the fix string from the fixed format specifier.
8267     SmallString<128> buf;
8268     llvm::raw_svector_ostream os(buf);
8269     fixedFS.toString(os);
8270 
8271     EmitFormatDiagnostic(
8272         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8273                       << Ex->getType() << false << Ex->getSourceRange(),
8274         Ex->getBeginLoc(),
8275         /*IsStringLocation*/ false,
8276         getSpecifierRange(startSpecifier, specifierLen),
8277         FixItHint::CreateReplacement(
8278             getSpecifierRange(startSpecifier, specifierLen), os.str()));
8279   } else {
8280     EmitFormatDiagnostic(S.PDiag(Diag)
8281                              << AT.getRepresentativeTypeName(S.Context)
8282                              << Ex->getType() << false << Ex->getSourceRange(),
8283                          Ex->getBeginLoc(),
8284                          /*IsStringLocation*/ false,
8285                          getSpecifierRange(startSpecifier, specifierLen));
8286   }
8287 
8288   return true;
8289 }
8290 
8291 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
8292                               const Expr *OrigFormatExpr,
8293                               ArrayRef<const Expr *> Args,
8294                               bool HasVAListArg, unsigned format_idx,
8295                               unsigned firstDataArg,
8296                               Sema::FormatStringType Type,
8297                               bool inFunctionCall,
8298                               Sema::VariadicCallType CallType,
8299                               llvm::SmallBitVector &CheckedVarArgs,
8300                               UncoveredArgHandler &UncoveredArg) {
8301   // CHECK: is the format string a wide literal?
8302   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
8303     CheckFormatHandler::EmitFormatDiagnostic(
8304         S, inFunctionCall, Args[format_idx],
8305         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
8306         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8307     return;
8308   }
8309 
8310   // Str - The format string.  NOTE: this is NOT null-terminated!
8311   StringRef StrRef = FExpr->getString();
8312   const char *Str = StrRef.data();
8313   // Account for cases where the string literal is truncated in a declaration.
8314   const ConstantArrayType *T =
8315     S.Context.getAsConstantArrayType(FExpr->getType());
8316   assert(T && "String literal not of constant array type!");
8317   size_t TypeSize = T->getSize().getZExtValue();
8318   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8319   const unsigned numDataArgs = Args.size() - firstDataArg;
8320 
8321   // Emit a warning if the string literal is truncated and does not contain an
8322   // embedded null character.
8323   if (TypeSize <= StrRef.size() &&
8324       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
8325     CheckFormatHandler::EmitFormatDiagnostic(
8326         S, inFunctionCall, Args[format_idx],
8327         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
8328         FExpr->getBeginLoc(),
8329         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
8330     return;
8331   }
8332 
8333   // CHECK: empty format string?
8334   if (StrLen == 0 && numDataArgs > 0) {
8335     CheckFormatHandler::EmitFormatDiagnostic(
8336         S, inFunctionCall, Args[format_idx],
8337         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
8338         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
8339     return;
8340   }
8341 
8342   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
8343       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
8344       Type == Sema::FST_OSTrace) {
8345     CheckPrintfHandler H(
8346         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
8347         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
8348         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
8349         CheckedVarArgs, UncoveredArg);
8350 
8351     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
8352                                                   S.getLangOpts(),
8353                                                   S.Context.getTargetInfo(),
8354                                             Type == Sema::FST_FreeBSDKPrintf))
8355       H.DoneProcessing();
8356   } else if (Type == Sema::FST_Scanf) {
8357     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
8358                         numDataArgs, Str, HasVAListArg, Args, format_idx,
8359                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
8360 
8361     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
8362                                                  S.getLangOpts(),
8363                                                  S.Context.getTargetInfo()))
8364       H.DoneProcessing();
8365   } // TODO: handle other formats
8366 }
8367 
8368 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
8369   // Str - The format string.  NOTE: this is NOT null-terminated!
8370   StringRef StrRef = FExpr->getString();
8371   const char *Str = StrRef.data();
8372   // Account for cases where the string literal is truncated in a declaration.
8373   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
8374   assert(T && "String literal not of constant array type!");
8375   size_t TypeSize = T->getSize().getZExtValue();
8376   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
8377   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
8378                                                          getLangOpts(),
8379                                                          Context.getTargetInfo());
8380 }
8381 
8382 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
8383 
8384 // Returns the related absolute value function that is larger, of 0 if one
8385 // does not exist.
8386 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
8387   switch (AbsFunction) {
8388   default:
8389     return 0;
8390 
8391   case Builtin::BI__builtin_abs:
8392     return Builtin::BI__builtin_labs;
8393   case Builtin::BI__builtin_labs:
8394     return Builtin::BI__builtin_llabs;
8395   case Builtin::BI__builtin_llabs:
8396     return 0;
8397 
8398   case Builtin::BI__builtin_fabsf:
8399     return Builtin::BI__builtin_fabs;
8400   case Builtin::BI__builtin_fabs:
8401     return Builtin::BI__builtin_fabsl;
8402   case Builtin::BI__builtin_fabsl:
8403     return 0;
8404 
8405   case Builtin::BI__builtin_cabsf:
8406     return Builtin::BI__builtin_cabs;
8407   case Builtin::BI__builtin_cabs:
8408     return Builtin::BI__builtin_cabsl;
8409   case Builtin::BI__builtin_cabsl:
8410     return 0;
8411 
8412   case Builtin::BIabs:
8413     return Builtin::BIlabs;
8414   case Builtin::BIlabs:
8415     return Builtin::BIllabs;
8416   case Builtin::BIllabs:
8417     return 0;
8418 
8419   case Builtin::BIfabsf:
8420     return Builtin::BIfabs;
8421   case Builtin::BIfabs:
8422     return Builtin::BIfabsl;
8423   case Builtin::BIfabsl:
8424     return 0;
8425 
8426   case Builtin::BIcabsf:
8427    return Builtin::BIcabs;
8428   case Builtin::BIcabs:
8429     return Builtin::BIcabsl;
8430   case Builtin::BIcabsl:
8431     return 0;
8432   }
8433 }
8434 
8435 // Returns the argument type of the absolute value function.
8436 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
8437                                              unsigned AbsType) {
8438   if (AbsType == 0)
8439     return QualType();
8440 
8441   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
8442   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
8443   if (Error != ASTContext::GE_None)
8444     return QualType();
8445 
8446   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
8447   if (!FT)
8448     return QualType();
8449 
8450   if (FT->getNumParams() != 1)
8451     return QualType();
8452 
8453   return FT->getParamType(0);
8454 }
8455 
8456 // Returns the best absolute value function, or zero, based on type and
8457 // current absolute value function.
8458 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
8459                                    unsigned AbsFunctionKind) {
8460   unsigned BestKind = 0;
8461   uint64_t ArgSize = Context.getTypeSize(ArgType);
8462   for (unsigned Kind = AbsFunctionKind; Kind != 0;
8463        Kind = getLargerAbsoluteValueFunction(Kind)) {
8464     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
8465     if (Context.getTypeSize(ParamType) >= ArgSize) {
8466       if (BestKind == 0)
8467         BestKind = Kind;
8468       else if (Context.hasSameType(ParamType, ArgType)) {
8469         BestKind = Kind;
8470         break;
8471       }
8472     }
8473   }
8474   return BestKind;
8475 }
8476 
8477 enum AbsoluteValueKind {
8478   AVK_Integer,
8479   AVK_Floating,
8480   AVK_Complex
8481 };
8482 
8483 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
8484   if (T->isIntegralOrEnumerationType())
8485     return AVK_Integer;
8486   if (T->isRealFloatingType())
8487     return AVK_Floating;
8488   if (T->isAnyComplexType())
8489     return AVK_Complex;
8490 
8491   llvm_unreachable("Type not integer, floating, or complex");
8492 }
8493 
8494 // Changes the absolute value function to a different type.  Preserves whether
8495 // the function is a builtin.
8496 static unsigned changeAbsFunction(unsigned AbsKind,
8497                                   AbsoluteValueKind ValueKind) {
8498   switch (ValueKind) {
8499   case AVK_Integer:
8500     switch (AbsKind) {
8501     default:
8502       return 0;
8503     case Builtin::BI__builtin_fabsf:
8504     case Builtin::BI__builtin_fabs:
8505     case Builtin::BI__builtin_fabsl:
8506     case Builtin::BI__builtin_cabsf:
8507     case Builtin::BI__builtin_cabs:
8508     case Builtin::BI__builtin_cabsl:
8509       return Builtin::BI__builtin_abs;
8510     case Builtin::BIfabsf:
8511     case Builtin::BIfabs:
8512     case Builtin::BIfabsl:
8513     case Builtin::BIcabsf:
8514     case Builtin::BIcabs:
8515     case Builtin::BIcabsl:
8516       return Builtin::BIabs;
8517     }
8518   case AVK_Floating:
8519     switch (AbsKind) {
8520     default:
8521       return 0;
8522     case Builtin::BI__builtin_abs:
8523     case Builtin::BI__builtin_labs:
8524     case Builtin::BI__builtin_llabs:
8525     case Builtin::BI__builtin_cabsf:
8526     case Builtin::BI__builtin_cabs:
8527     case Builtin::BI__builtin_cabsl:
8528       return Builtin::BI__builtin_fabsf;
8529     case Builtin::BIabs:
8530     case Builtin::BIlabs:
8531     case Builtin::BIllabs:
8532     case Builtin::BIcabsf:
8533     case Builtin::BIcabs:
8534     case Builtin::BIcabsl:
8535       return Builtin::BIfabsf;
8536     }
8537   case AVK_Complex:
8538     switch (AbsKind) {
8539     default:
8540       return 0;
8541     case Builtin::BI__builtin_abs:
8542     case Builtin::BI__builtin_labs:
8543     case Builtin::BI__builtin_llabs:
8544     case Builtin::BI__builtin_fabsf:
8545     case Builtin::BI__builtin_fabs:
8546     case Builtin::BI__builtin_fabsl:
8547       return Builtin::BI__builtin_cabsf;
8548     case Builtin::BIabs:
8549     case Builtin::BIlabs:
8550     case Builtin::BIllabs:
8551     case Builtin::BIfabsf:
8552     case Builtin::BIfabs:
8553     case Builtin::BIfabsl:
8554       return Builtin::BIcabsf;
8555     }
8556   }
8557   llvm_unreachable("Unable to convert function");
8558 }
8559 
8560 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
8561   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
8562   if (!FnInfo)
8563     return 0;
8564 
8565   switch (FDecl->getBuiltinID()) {
8566   default:
8567     return 0;
8568   case Builtin::BI__builtin_abs:
8569   case Builtin::BI__builtin_fabs:
8570   case Builtin::BI__builtin_fabsf:
8571   case Builtin::BI__builtin_fabsl:
8572   case Builtin::BI__builtin_labs:
8573   case Builtin::BI__builtin_llabs:
8574   case Builtin::BI__builtin_cabs:
8575   case Builtin::BI__builtin_cabsf:
8576   case Builtin::BI__builtin_cabsl:
8577   case Builtin::BIabs:
8578   case Builtin::BIlabs:
8579   case Builtin::BIllabs:
8580   case Builtin::BIfabs:
8581   case Builtin::BIfabsf:
8582   case Builtin::BIfabsl:
8583   case Builtin::BIcabs:
8584   case Builtin::BIcabsf:
8585   case Builtin::BIcabsl:
8586     return FDecl->getBuiltinID();
8587   }
8588   llvm_unreachable("Unknown Builtin type");
8589 }
8590 
8591 // If the replacement is valid, emit a note with replacement function.
8592 // Additionally, suggest including the proper header if not already included.
8593 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
8594                             unsigned AbsKind, QualType ArgType) {
8595   bool EmitHeaderHint = true;
8596   const char *HeaderName = nullptr;
8597   const char *FunctionName = nullptr;
8598   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
8599     FunctionName = "std::abs";
8600     if (ArgType->isIntegralOrEnumerationType()) {
8601       HeaderName = "cstdlib";
8602     } else if (ArgType->isRealFloatingType()) {
8603       HeaderName = "cmath";
8604     } else {
8605       llvm_unreachable("Invalid Type");
8606     }
8607 
8608     // Lookup all std::abs
8609     if (NamespaceDecl *Std = S.getStdNamespace()) {
8610       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
8611       R.suppressDiagnostics();
8612       S.LookupQualifiedName(R, Std);
8613 
8614       for (const auto *I : R) {
8615         const FunctionDecl *FDecl = nullptr;
8616         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
8617           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
8618         } else {
8619           FDecl = dyn_cast<FunctionDecl>(I);
8620         }
8621         if (!FDecl)
8622           continue;
8623 
8624         // Found std::abs(), check that they are the right ones.
8625         if (FDecl->getNumParams() != 1)
8626           continue;
8627 
8628         // Check that the parameter type can handle the argument.
8629         QualType ParamType = FDecl->getParamDecl(0)->getType();
8630         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
8631             S.Context.getTypeSize(ArgType) <=
8632                 S.Context.getTypeSize(ParamType)) {
8633           // Found a function, don't need the header hint.
8634           EmitHeaderHint = false;
8635           break;
8636         }
8637       }
8638     }
8639   } else {
8640     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
8641     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
8642 
8643     if (HeaderName) {
8644       DeclarationName DN(&S.Context.Idents.get(FunctionName));
8645       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
8646       R.suppressDiagnostics();
8647       S.LookupName(R, S.getCurScope());
8648 
8649       if (R.isSingleResult()) {
8650         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
8651         if (FD && FD->getBuiltinID() == AbsKind) {
8652           EmitHeaderHint = false;
8653         } else {
8654           return;
8655         }
8656       } else if (!R.empty()) {
8657         return;
8658       }
8659     }
8660   }
8661 
8662   S.Diag(Loc, diag::note_replace_abs_function)
8663       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
8664 
8665   if (!HeaderName)
8666     return;
8667 
8668   if (!EmitHeaderHint)
8669     return;
8670 
8671   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
8672                                                     << FunctionName;
8673 }
8674 
8675 template <std::size_t StrLen>
8676 static bool IsStdFunction(const FunctionDecl *FDecl,
8677                           const char (&Str)[StrLen]) {
8678   if (!FDecl)
8679     return false;
8680   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
8681     return false;
8682   if (!FDecl->isInStdNamespace())
8683     return false;
8684 
8685   return true;
8686 }
8687 
8688 // Warn when using the wrong abs() function.
8689 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
8690                                       const FunctionDecl *FDecl) {
8691   if (Call->getNumArgs() != 1)
8692     return;
8693 
8694   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
8695   bool IsStdAbs = IsStdFunction(FDecl, "abs");
8696   if (AbsKind == 0 && !IsStdAbs)
8697     return;
8698 
8699   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
8700   QualType ParamType = Call->getArg(0)->getType();
8701 
8702   // Unsigned types cannot be negative.  Suggest removing the absolute value
8703   // function call.
8704   if (ArgType->isUnsignedIntegerType()) {
8705     const char *FunctionName =
8706         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
8707     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
8708     Diag(Call->getExprLoc(), diag::note_remove_abs)
8709         << FunctionName
8710         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
8711     return;
8712   }
8713 
8714   // Taking the absolute value of a pointer is very suspicious, they probably
8715   // wanted to index into an array, dereference a pointer, call a function, etc.
8716   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
8717     unsigned DiagType = 0;
8718     if (ArgType->isFunctionType())
8719       DiagType = 1;
8720     else if (ArgType->isArrayType())
8721       DiagType = 2;
8722 
8723     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
8724     return;
8725   }
8726 
8727   // std::abs has overloads which prevent most of the absolute value problems
8728   // from occurring.
8729   if (IsStdAbs)
8730     return;
8731 
8732   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
8733   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
8734 
8735   // The argument and parameter are the same kind.  Check if they are the right
8736   // size.
8737   if (ArgValueKind == ParamValueKind) {
8738     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
8739       return;
8740 
8741     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
8742     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
8743         << FDecl << ArgType << ParamType;
8744 
8745     if (NewAbsKind == 0)
8746       return;
8747 
8748     emitReplacement(*this, Call->getExprLoc(),
8749                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8750     return;
8751   }
8752 
8753   // ArgValueKind != ParamValueKind
8754   // The wrong type of absolute value function was used.  Attempt to find the
8755   // proper one.
8756   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
8757   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
8758   if (NewAbsKind == 0)
8759     return;
8760 
8761   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
8762       << FDecl << ParamValueKind << ArgValueKind;
8763 
8764   emitReplacement(*this, Call->getExprLoc(),
8765                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
8766 }
8767 
8768 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
8769 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
8770                                 const FunctionDecl *FDecl) {
8771   if (!Call || !FDecl) return;
8772 
8773   // Ignore template specializations and macros.
8774   if (inTemplateInstantiation()) return;
8775   if (Call->getExprLoc().isMacroID()) return;
8776 
8777   // Only care about the one template argument, two function parameter std::max
8778   if (Call->getNumArgs() != 2) return;
8779   if (!IsStdFunction(FDecl, "max")) return;
8780   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
8781   if (!ArgList) return;
8782   if (ArgList->size() != 1) return;
8783 
8784   // Check that template type argument is unsigned integer.
8785   const auto& TA = ArgList->get(0);
8786   if (TA.getKind() != TemplateArgument::Type) return;
8787   QualType ArgType = TA.getAsType();
8788   if (!ArgType->isUnsignedIntegerType()) return;
8789 
8790   // See if either argument is a literal zero.
8791   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
8792     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
8793     if (!MTE) return false;
8794     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
8795     if (!Num) return false;
8796     if (Num->getValue() != 0) return false;
8797     return true;
8798   };
8799 
8800   const Expr *FirstArg = Call->getArg(0);
8801   const Expr *SecondArg = Call->getArg(1);
8802   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
8803   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
8804 
8805   // Only warn when exactly one argument is zero.
8806   if (IsFirstArgZero == IsSecondArgZero) return;
8807 
8808   SourceRange FirstRange = FirstArg->getSourceRange();
8809   SourceRange SecondRange = SecondArg->getSourceRange();
8810 
8811   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
8812 
8813   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
8814       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
8815 
8816   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
8817   SourceRange RemovalRange;
8818   if (IsFirstArgZero) {
8819     RemovalRange = SourceRange(FirstRange.getBegin(),
8820                                SecondRange.getBegin().getLocWithOffset(-1));
8821   } else {
8822     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
8823                                SecondRange.getEnd());
8824   }
8825 
8826   Diag(Call->getExprLoc(), diag::note_remove_max_call)
8827         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
8828         << FixItHint::CreateRemoval(RemovalRange);
8829 }
8830 
8831 //===--- CHECK: Standard memory functions ---------------------------------===//
8832 
8833 /// Takes the expression passed to the size_t parameter of functions
8834 /// such as memcmp, strncat, etc and warns if it's a comparison.
8835 ///
8836 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
8837 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
8838                                            IdentifierInfo *FnName,
8839                                            SourceLocation FnLoc,
8840                                            SourceLocation RParenLoc) {
8841   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
8842   if (!Size)
8843     return false;
8844 
8845   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
8846   if (!Size->isComparisonOp() && !Size->isLogicalOp())
8847     return false;
8848 
8849   SourceRange SizeRange = Size->getSourceRange();
8850   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
8851       << SizeRange << FnName;
8852   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
8853       << FnName
8854       << FixItHint::CreateInsertion(
8855              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
8856       << FixItHint::CreateRemoval(RParenLoc);
8857   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
8858       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
8859       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
8860                                     ")");
8861 
8862   return true;
8863 }
8864 
8865 /// Determine whether the given type is or contains a dynamic class type
8866 /// (e.g., whether it has a vtable).
8867 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
8868                                                      bool &IsContained) {
8869   // Look through array types while ignoring qualifiers.
8870   const Type *Ty = T->getBaseElementTypeUnsafe();
8871   IsContained = false;
8872 
8873   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
8874   RD = RD ? RD->getDefinition() : nullptr;
8875   if (!RD || RD->isInvalidDecl())
8876     return nullptr;
8877 
8878   if (RD->isDynamicClass())
8879     return RD;
8880 
8881   // Check all the fields.  If any bases were dynamic, the class is dynamic.
8882   // It's impossible for a class to transitively contain itself by value, so
8883   // infinite recursion is impossible.
8884   for (auto *FD : RD->fields()) {
8885     bool SubContained;
8886     if (const CXXRecordDecl *ContainedRD =
8887             getContainedDynamicClass(FD->getType(), SubContained)) {
8888       IsContained = true;
8889       return ContainedRD;
8890     }
8891   }
8892 
8893   return nullptr;
8894 }
8895 
8896 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
8897   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
8898     if (Unary->getKind() == UETT_SizeOf)
8899       return Unary;
8900   return nullptr;
8901 }
8902 
8903 /// If E is a sizeof expression, returns its argument expression,
8904 /// otherwise returns NULL.
8905 static const Expr *getSizeOfExprArg(const Expr *E) {
8906   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8907     if (!SizeOf->isArgumentType())
8908       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
8909   return nullptr;
8910 }
8911 
8912 /// If E is a sizeof expression, returns its argument type.
8913 static QualType getSizeOfArgType(const Expr *E) {
8914   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
8915     return SizeOf->getTypeOfArgument();
8916   return QualType();
8917 }
8918 
8919 namespace {
8920 
8921 struct SearchNonTrivialToInitializeField
8922     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
8923   using Super =
8924       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
8925 
8926   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
8927 
8928   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
8929                      SourceLocation SL) {
8930     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8931       asDerived().visitArray(PDIK, AT, SL);
8932       return;
8933     }
8934 
8935     Super::visitWithKind(PDIK, FT, SL);
8936   }
8937 
8938   void visitARCStrong(QualType FT, SourceLocation SL) {
8939     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8940   }
8941   void visitARCWeak(QualType FT, SourceLocation SL) {
8942     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
8943   }
8944   void visitStruct(QualType FT, SourceLocation SL) {
8945     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8946       visit(FD->getType(), FD->getLocation());
8947   }
8948   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
8949                   const ArrayType *AT, SourceLocation SL) {
8950     visit(getContext().getBaseElementType(AT), SL);
8951   }
8952   void visitTrivial(QualType FT, SourceLocation SL) {}
8953 
8954   static void diag(QualType RT, const Expr *E, Sema &S) {
8955     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
8956   }
8957 
8958   ASTContext &getContext() { return S.getASTContext(); }
8959 
8960   const Expr *E;
8961   Sema &S;
8962 };
8963 
8964 struct SearchNonTrivialToCopyField
8965     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
8966   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
8967 
8968   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
8969 
8970   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
8971                      SourceLocation SL) {
8972     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
8973       asDerived().visitArray(PCK, AT, SL);
8974       return;
8975     }
8976 
8977     Super::visitWithKind(PCK, FT, SL);
8978   }
8979 
8980   void visitARCStrong(QualType FT, SourceLocation SL) {
8981     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8982   }
8983   void visitARCWeak(QualType FT, SourceLocation SL) {
8984     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
8985   }
8986   void visitStruct(QualType FT, SourceLocation SL) {
8987     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
8988       visit(FD->getType(), FD->getLocation());
8989   }
8990   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
8991                   SourceLocation SL) {
8992     visit(getContext().getBaseElementType(AT), SL);
8993   }
8994   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
8995                 SourceLocation SL) {}
8996   void visitTrivial(QualType FT, SourceLocation SL) {}
8997   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
8998 
8999   static void diag(QualType RT, const Expr *E, Sema &S) {
9000     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9001   }
9002 
9003   ASTContext &getContext() { return S.getASTContext(); }
9004 
9005   const Expr *E;
9006   Sema &S;
9007 };
9008 
9009 }
9010 
9011 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9012 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9013   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9014 
9015   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9016     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9017       return false;
9018 
9019     return doesExprLikelyComputeSize(BO->getLHS()) ||
9020            doesExprLikelyComputeSize(BO->getRHS());
9021   }
9022 
9023   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9024 }
9025 
9026 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9027 ///
9028 /// \code
9029 ///   #define MACRO 0
9030 ///   foo(MACRO);
9031 ///   foo(0);
9032 /// \endcode
9033 ///
9034 /// This should return true for the first call to foo, but not for the second
9035 /// (regardless of whether foo is a macro or function).
9036 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9037                                         SourceLocation CallLoc,
9038                                         SourceLocation ArgLoc) {
9039   if (!CallLoc.isMacroID())
9040     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9041 
9042   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9043          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9044 }
9045 
9046 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9047 /// last two arguments transposed.
9048 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9049   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9050     return;
9051 
9052   const Expr *SizeArg =
9053     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9054 
9055   auto isLiteralZero = [](const Expr *E) {
9056     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9057   };
9058 
9059   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9060   SourceLocation CallLoc = Call->getRParenLoc();
9061   SourceManager &SM = S.getSourceManager();
9062   if (isLiteralZero(SizeArg) &&
9063       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9064 
9065     SourceLocation DiagLoc = SizeArg->getExprLoc();
9066 
9067     // Some platforms #define bzero to __builtin_memset. See if this is the
9068     // case, and if so, emit a better diagnostic.
9069     if (BId == Builtin::BIbzero ||
9070         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9071                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9072       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9073       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9074     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9075       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9076       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9077     }
9078     return;
9079   }
9080 
9081   // If the second argument to a memset is a sizeof expression and the third
9082   // isn't, this is also likely an error. This should catch
9083   // 'memset(buf, sizeof(buf), 0xff)'.
9084   if (BId == Builtin::BImemset &&
9085       doesExprLikelyComputeSize(Call->getArg(1)) &&
9086       !doesExprLikelyComputeSize(Call->getArg(2))) {
9087     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9088     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9089     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9090     return;
9091   }
9092 }
9093 
9094 /// Check for dangerous or invalid arguments to memset().
9095 ///
9096 /// This issues warnings on known problematic, dangerous or unspecified
9097 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9098 /// function calls.
9099 ///
9100 /// \param Call The call expression to diagnose.
9101 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9102                                    unsigned BId,
9103                                    IdentifierInfo *FnName) {
9104   assert(BId != 0);
9105 
9106   // It is possible to have a non-standard definition of memset.  Validate
9107   // we have enough arguments, and if not, abort further checking.
9108   unsigned ExpectedNumArgs =
9109       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9110   if (Call->getNumArgs() < ExpectedNumArgs)
9111     return;
9112 
9113   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9114                       BId == Builtin::BIstrndup ? 1 : 2);
9115   unsigned LenArg =
9116       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9117   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9118 
9119   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9120                                      Call->getBeginLoc(), Call->getRParenLoc()))
9121     return;
9122 
9123   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9124   CheckMemaccessSize(*this, BId, Call);
9125 
9126   // We have special checking when the length is a sizeof expression.
9127   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9128   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9129   llvm::FoldingSetNodeID SizeOfArgID;
9130 
9131   // Although widely used, 'bzero' is not a standard function. Be more strict
9132   // with the argument types before allowing diagnostics and only allow the
9133   // form bzero(ptr, sizeof(...)).
9134   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9135   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9136     return;
9137 
9138   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9139     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9140     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9141 
9142     QualType DestTy = Dest->getType();
9143     QualType PointeeTy;
9144     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9145       PointeeTy = DestPtrTy->getPointeeType();
9146 
9147       // Never warn about void type pointers. This can be used to suppress
9148       // false positives.
9149       if (PointeeTy->isVoidType())
9150         continue;
9151 
9152       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9153       // actually comparing the expressions for equality. Because computing the
9154       // expression IDs can be expensive, we only do this if the diagnostic is
9155       // enabled.
9156       if (SizeOfArg &&
9157           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9158                            SizeOfArg->getExprLoc())) {
9159         // We only compute IDs for expressions if the warning is enabled, and
9160         // cache the sizeof arg's ID.
9161         if (SizeOfArgID == llvm::FoldingSetNodeID())
9162           SizeOfArg->Profile(SizeOfArgID, Context, true);
9163         llvm::FoldingSetNodeID DestID;
9164         Dest->Profile(DestID, Context, true);
9165         if (DestID == SizeOfArgID) {
9166           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9167           //       over sizeof(src) as well.
9168           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9169           StringRef ReadableName = FnName->getName();
9170 
9171           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9172             if (UnaryOp->getOpcode() == UO_AddrOf)
9173               ActionIdx = 1; // If its an address-of operator, just remove it.
9174           if (!PointeeTy->isIncompleteType() &&
9175               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9176             ActionIdx = 2; // If the pointee's size is sizeof(char),
9177                            // suggest an explicit length.
9178 
9179           // If the function is defined as a builtin macro, do not show macro
9180           // expansion.
9181           SourceLocation SL = SizeOfArg->getExprLoc();
9182           SourceRange DSR = Dest->getSourceRange();
9183           SourceRange SSR = SizeOfArg->getSourceRange();
9184           SourceManager &SM = getSourceManager();
9185 
9186           if (SM.isMacroArgExpansion(SL)) {
9187             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9188             SL = SM.getSpellingLoc(SL);
9189             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9190                              SM.getSpellingLoc(DSR.getEnd()));
9191             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9192                              SM.getSpellingLoc(SSR.getEnd()));
9193           }
9194 
9195           DiagRuntimeBehavior(SL, SizeOfArg,
9196                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9197                                 << ReadableName
9198                                 << PointeeTy
9199                                 << DestTy
9200                                 << DSR
9201                                 << SSR);
9202           DiagRuntimeBehavior(SL, SizeOfArg,
9203                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9204                                 << ActionIdx
9205                                 << SSR);
9206 
9207           break;
9208         }
9209       }
9210 
9211       // Also check for cases where the sizeof argument is the exact same
9212       // type as the memory argument, and where it points to a user-defined
9213       // record type.
9214       if (SizeOfArgTy != QualType()) {
9215         if (PointeeTy->isRecordType() &&
9216             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9217           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9218                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9219                                 << FnName << SizeOfArgTy << ArgIdx
9220                                 << PointeeTy << Dest->getSourceRange()
9221                                 << LenExpr->getSourceRange());
9222           break;
9223         }
9224       }
9225     } else if (DestTy->isArrayType()) {
9226       PointeeTy = DestTy;
9227     }
9228 
9229     if (PointeeTy == QualType())
9230       continue;
9231 
9232     // Always complain about dynamic classes.
9233     bool IsContained;
9234     if (const CXXRecordDecl *ContainedRD =
9235             getContainedDynamicClass(PointeeTy, IsContained)) {
9236 
9237       unsigned OperationType = 0;
9238       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9239       // "overwritten" if we're warning about the destination for any call
9240       // but memcmp; otherwise a verb appropriate to the call.
9241       if (ArgIdx != 0 || IsCmp) {
9242         if (BId == Builtin::BImemcpy)
9243           OperationType = 1;
9244         else if(BId == Builtin::BImemmove)
9245           OperationType = 2;
9246         else if (IsCmp)
9247           OperationType = 3;
9248       }
9249 
9250       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9251                           PDiag(diag::warn_dyn_class_memaccess)
9252                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9253                               << IsContained << ContainedRD << OperationType
9254                               << Call->getCallee()->getSourceRange());
9255     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9256              BId != Builtin::BImemset)
9257       DiagRuntimeBehavior(
9258         Dest->getExprLoc(), Dest,
9259         PDiag(diag::warn_arc_object_memaccess)
9260           << ArgIdx << FnName << PointeeTy
9261           << Call->getCallee()->getSourceRange());
9262     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9263       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9264           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9265         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9266                             PDiag(diag::warn_cstruct_memaccess)
9267                                 << ArgIdx << FnName << PointeeTy << 0);
9268         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9269       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9270                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9271         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9272                             PDiag(diag::warn_cstruct_memaccess)
9273                                 << ArgIdx << FnName << PointeeTy << 1);
9274         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
9275       } else {
9276         continue;
9277       }
9278     } else
9279       continue;
9280 
9281     DiagRuntimeBehavior(
9282       Dest->getExprLoc(), Dest,
9283       PDiag(diag::note_bad_memaccess_silence)
9284         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
9285     break;
9286   }
9287 }
9288 
9289 // A little helper routine: ignore addition and subtraction of integer literals.
9290 // This intentionally does not ignore all integer constant expressions because
9291 // we don't want to remove sizeof().
9292 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
9293   Ex = Ex->IgnoreParenCasts();
9294 
9295   while (true) {
9296     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
9297     if (!BO || !BO->isAdditiveOp())
9298       break;
9299 
9300     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
9301     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
9302 
9303     if (isa<IntegerLiteral>(RHS))
9304       Ex = LHS;
9305     else if (isa<IntegerLiteral>(LHS))
9306       Ex = RHS;
9307     else
9308       break;
9309   }
9310 
9311   return Ex;
9312 }
9313 
9314 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
9315                                                       ASTContext &Context) {
9316   // Only handle constant-sized or VLAs, but not flexible members.
9317   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
9318     // Only issue the FIXIT for arrays of size > 1.
9319     if (CAT->getSize().getSExtValue() <= 1)
9320       return false;
9321   } else if (!Ty->isVariableArrayType()) {
9322     return false;
9323   }
9324   return true;
9325 }
9326 
9327 // Warn if the user has made the 'size' argument to strlcpy or strlcat
9328 // be the size of the source, instead of the destination.
9329 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
9330                                     IdentifierInfo *FnName) {
9331 
9332   // Don't crash if the user has the wrong number of arguments
9333   unsigned NumArgs = Call->getNumArgs();
9334   if ((NumArgs != 3) && (NumArgs != 4))
9335     return;
9336 
9337   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
9338   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
9339   const Expr *CompareWithSrc = nullptr;
9340 
9341   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
9342                                      Call->getBeginLoc(), Call->getRParenLoc()))
9343     return;
9344 
9345   // Look for 'strlcpy(dst, x, sizeof(x))'
9346   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
9347     CompareWithSrc = Ex;
9348   else {
9349     // Look for 'strlcpy(dst, x, strlen(x))'
9350     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
9351       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
9352           SizeCall->getNumArgs() == 1)
9353         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
9354     }
9355   }
9356 
9357   if (!CompareWithSrc)
9358     return;
9359 
9360   // Determine if the argument to sizeof/strlen is equal to the source
9361   // argument.  In principle there's all kinds of things you could do
9362   // here, for instance creating an == expression and evaluating it with
9363   // EvaluateAsBooleanCondition, but this uses a more direct technique:
9364   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
9365   if (!SrcArgDRE)
9366     return;
9367 
9368   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
9369   if (!CompareWithSrcDRE ||
9370       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
9371     return;
9372 
9373   const Expr *OriginalSizeArg = Call->getArg(2);
9374   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
9375       << OriginalSizeArg->getSourceRange() << FnName;
9376 
9377   // Output a FIXIT hint if the destination is an array (rather than a
9378   // pointer to an array).  This could be enhanced to handle some
9379   // pointers if we know the actual size, like if DstArg is 'array+2'
9380   // we could say 'sizeof(array)-2'.
9381   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
9382   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
9383     return;
9384 
9385   SmallString<128> sizeString;
9386   llvm::raw_svector_ostream OS(sizeString);
9387   OS << "sizeof(";
9388   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9389   OS << ")";
9390 
9391   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
9392       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
9393                                       OS.str());
9394 }
9395 
9396 /// Check if two expressions refer to the same declaration.
9397 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
9398   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
9399     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
9400       return D1->getDecl() == D2->getDecl();
9401   return false;
9402 }
9403 
9404 static const Expr *getStrlenExprArg(const Expr *E) {
9405   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9406     const FunctionDecl *FD = CE->getDirectCallee();
9407     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
9408       return nullptr;
9409     return CE->getArg(0)->IgnoreParenCasts();
9410   }
9411   return nullptr;
9412 }
9413 
9414 // Warn on anti-patterns as the 'size' argument to strncat.
9415 // The correct size argument should look like following:
9416 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
9417 void Sema::CheckStrncatArguments(const CallExpr *CE,
9418                                  IdentifierInfo *FnName) {
9419   // Don't crash if the user has the wrong number of arguments.
9420   if (CE->getNumArgs() < 3)
9421     return;
9422   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
9423   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
9424   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
9425 
9426   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
9427                                      CE->getRParenLoc()))
9428     return;
9429 
9430   // Identify common expressions, which are wrongly used as the size argument
9431   // to strncat and may lead to buffer overflows.
9432   unsigned PatternType = 0;
9433   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
9434     // - sizeof(dst)
9435     if (referToTheSameDecl(SizeOfArg, DstArg))
9436       PatternType = 1;
9437     // - sizeof(src)
9438     else if (referToTheSameDecl(SizeOfArg, SrcArg))
9439       PatternType = 2;
9440   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
9441     if (BE->getOpcode() == BO_Sub) {
9442       const Expr *L = BE->getLHS()->IgnoreParenCasts();
9443       const Expr *R = BE->getRHS()->IgnoreParenCasts();
9444       // - sizeof(dst) - strlen(dst)
9445       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
9446           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
9447         PatternType = 1;
9448       // - sizeof(src) - (anything)
9449       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
9450         PatternType = 2;
9451     }
9452   }
9453 
9454   if (PatternType == 0)
9455     return;
9456 
9457   // Generate the diagnostic.
9458   SourceLocation SL = LenArg->getBeginLoc();
9459   SourceRange SR = LenArg->getSourceRange();
9460   SourceManager &SM = getSourceManager();
9461 
9462   // If the function is defined as a builtin macro, do not show macro expansion.
9463   if (SM.isMacroArgExpansion(SL)) {
9464     SL = SM.getSpellingLoc(SL);
9465     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
9466                      SM.getSpellingLoc(SR.getEnd()));
9467   }
9468 
9469   // Check if the destination is an array (rather than a pointer to an array).
9470   QualType DstTy = DstArg->getType();
9471   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
9472                                                                     Context);
9473   if (!isKnownSizeArray) {
9474     if (PatternType == 1)
9475       Diag(SL, diag::warn_strncat_wrong_size) << SR;
9476     else
9477       Diag(SL, diag::warn_strncat_src_size) << SR;
9478     return;
9479   }
9480 
9481   if (PatternType == 1)
9482     Diag(SL, diag::warn_strncat_large_size) << SR;
9483   else
9484     Diag(SL, diag::warn_strncat_src_size) << SR;
9485 
9486   SmallString<128> sizeString;
9487   llvm::raw_svector_ostream OS(sizeString);
9488   OS << "sizeof(";
9489   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9490   OS << ") - ";
9491   OS << "strlen(";
9492   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
9493   OS << ") - 1";
9494 
9495   Diag(SL, diag::note_strncat_wrong_size)
9496     << FixItHint::CreateReplacement(SR, OS.str());
9497 }
9498 
9499 void
9500 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
9501                          SourceLocation ReturnLoc,
9502                          bool isObjCMethod,
9503                          const AttrVec *Attrs,
9504                          const FunctionDecl *FD) {
9505   // Check if the return value is null but should not be.
9506   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
9507        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
9508       CheckNonNullExpr(*this, RetValExp))
9509     Diag(ReturnLoc, diag::warn_null_ret)
9510       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
9511 
9512   // C++11 [basic.stc.dynamic.allocation]p4:
9513   //   If an allocation function declared with a non-throwing
9514   //   exception-specification fails to allocate storage, it shall return
9515   //   a null pointer. Any other allocation function that fails to allocate
9516   //   storage shall indicate failure only by throwing an exception [...]
9517   if (FD) {
9518     OverloadedOperatorKind Op = FD->getOverloadedOperator();
9519     if (Op == OO_New || Op == OO_Array_New) {
9520       const FunctionProtoType *Proto
9521         = FD->getType()->castAs<FunctionProtoType>();
9522       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
9523           CheckNonNullExpr(*this, RetValExp))
9524         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
9525           << FD << getLangOpts().CPlusPlus11;
9526     }
9527   }
9528 }
9529 
9530 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
9531 
9532 /// Check for comparisons of floating point operands using != and ==.
9533 /// Issue a warning if these are no self-comparisons, as they are not likely
9534 /// to do what the programmer intended.
9535 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
9536   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
9537   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
9538 
9539   // Special case: check for x == x (which is OK).
9540   // Do not emit warnings for such cases.
9541   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
9542     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
9543       if (DRL->getDecl() == DRR->getDecl())
9544         return;
9545 
9546   // Special case: check for comparisons against literals that can be exactly
9547   //  represented by APFloat.  In such cases, do not emit a warning.  This
9548   //  is a heuristic: often comparison against such literals are used to
9549   //  detect if a value in a variable has not changed.  This clearly can
9550   //  lead to false negatives.
9551   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
9552     if (FLL->isExact())
9553       return;
9554   } else
9555     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
9556       if (FLR->isExact())
9557         return;
9558 
9559   // Check for comparisons with builtin types.
9560   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
9561     if (CL->getBuiltinCallee())
9562       return;
9563 
9564   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
9565     if (CR->getBuiltinCallee())
9566       return;
9567 
9568   // Emit the diagnostic.
9569   Diag(Loc, diag::warn_floatingpoint_eq)
9570     << LHS->getSourceRange() << RHS->getSourceRange();
9571 }
9572 
9573 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
9574 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
9575 
9576 namespace {
9577 
9578 /// Structure recording the 'active' range of an integer-valued
9579 /// expression.
9580 struct IntRange {
9581   /// The number of bits active in the int.
9582   unsigned Width;
9583 
9584   /// True if the int is known not to have negative values.
9585   bool NonNegative;
9586 
9587   IntRange(unsigned Width, bool NonNegative)
9588       : Width(Width), NonNegative(NonNegative) {}
9589 
9590   /// Returns the range of the bool type.
9591   static IntRange forBoolType() {
9592     return IntRange(1, true);
9593   }
9594 
9595   /// Returns the range of an opaque value of the given integral type.
9596   static IntRange forValueOfType(ASTContext &C, QualType T) {
9597     return forValueOfCanonicalType(C,
9598                           T->getCanonicalTypeInternal().getTypePtr());
9599   }
9600 
9601   /// Returns the range of an opaque value of a canonical integral type.
9602   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
9603     assert(T->isCanonicalUnqualified());
9604 
9605     if (const VectorType *VT = dyn_cast<VectorType>(T))
9606       T = VT->getElementType().getTypePtr();
9607     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9608       T = CT->getElementType().getTypePtr();
9609     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9610       T = AT->getValueType().getTypePtr();
9611 
9612     if (!C.getLangOpts().CPlusPlus) {
9613       // For enum types in C code, use the underlying datatype.
9614       if (const EnumType *ET = dyn_cast<EnumType>(T))
9615         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
9616     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
9617       // For enum types in C++, use the known bit width of the enumerators.
9618       EnumDecl *Enum = ET->getDecl();
9619       // In C++11, enums can have a fixed underlying type. Use this type to
9620       // compute the range.
9621       if (Enum->isFixed()) {
9622         return IntRange(C.getIntWidth(QualType(T, 0)),
9623                         !ET->isSignedIntegerOrEnumerationType());
9624       }
9625 
9626       unsigned NumPositive = Enum->getNumPositiveBits();
9627       unsigned NumNegative = Enum->getNumNegativeBits();
9628 
9629       if (NumNegative == 0)
9630         return IntRange(NumPositive, true/*NonNegative*/);
9631       else
9632         return IntRange(std::max(NumPositive + 1, NumNegative),
9633                         false/*NonNegative*/);
9634     }
9635 
9636     const BuiltinType *BT = cast<BuiltinType>(T);
9637     assert(BT->isInteger());
9638 
9639     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9640   }
9641 
9642   /// Returns the "target" range of a canonical integral type, i.e.
9643   /// the range of values expressible in the type.
9644   ///
9645   /// This matches forValueOfCanonicalType except that enums have the
9646   /// full range of their type, not the range of their enumerators.
9647   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
9648     assert(T->isCanonicalUnqualified());
9649 
9650     if (const VectorType *VT = dyn_cast<VectorType>(T))
9651       T = VT->getElementType().getTypePtr();
9652     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
9653       T = CT->getElementType().getTypePtr();
9654     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
9655       T = AT->getValueType().getTypePtr();
9656     if (const EnumType *ET = dyn_cast<EnumType>(T))
9657       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
9658 
9659     const BuiltinType *BT = cast<BuiltinType>(T);
9660     assert(BT->isInteger());
9661 
9662     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
9663   }
9664 
9665   /// Returns the supremum of two ranges: i.e. their conservative merge.
9666   static IntRange join(IntRange L, IntRange R) {
9667     return IntRange(std::max(L.Width, R.Width),
9668                     L.NonNegative && R.NonNegative);
9669   }
9670 
9671   /// Returns the infinum of two ranges: i.e. their aggressive merge.
9672   static IntRange meet(IntRange L, IntRange R) {
9673     return IntRange(std::min(L.Width, R.Width),
9674                     L.NonNegative || R.NonNegative);
9675   }
9676 };
9677 
9678 } // namespace
9679 
9680 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
9681                               unsigned MaxWidth) {
9682   if (value.isSigned() && value.isNegative())
9683     return IntRange(value.getMinSignedBits(), false);
9684 
9685   if (value.getBitWidth() > MaxWidth)
9686     value = value.trunc(MaxWidth);
9687 
9688   // isNonNegative() just checks the sign bit without considering
9689   // signedness.
9690   return IntRange(value.getActiveBits(), true);
9691 }
9692 
9693 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
9694                               unsigned MaxWidth) {
9695   if (result.isInt())
9696     return GetValueRange(C, result.getInt(), MaxWidth);
9697 
9698   if (result.isVector()) {
9699     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
9700     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
9701       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
9702       R = IntRange::join(R, El);
9703     }
9704     return R;
9705   }
9706 
9707   if (result.isComplexInt()) {
9708     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
9709     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
9710     return IntRange::join(R, I);
9711   }
9712 
9713   // This can happen with lossless casts to intptr_t of "based" lvalues.
9714   // Assume it might use arbitrary bits.
9715   // FIXME: The only reason we need to pass the type in here is to get
9716   // the sign right on this one case.  It would be nice if APValue
9717   // preserved this.
9718   assert(result.isLValue() || result.isAddrLabelDiff());
9719   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
9720 }
9721 
9722 static QualType GetExprType(const Expr *E) {
9723   QualType Ty = E->getType();
9724   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
9725     Ty = AtomicRHS->getValueType();
9726   return Ty;
9727 }
9728 
9729 /// Pseudo-evaluate the given integer expression, estimating the
9730 /// range of values it might take.
9731 ///
9732 /// \param MaxWidth - the width to which the value will be truncated
9733 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
9734   E = E->IgnoreParens();
9735 
9736   // Try a full evaluation first.
9737   Expr::EvalResult result;
9738   if (E->EvaluateAsRValue(result, C))
9739     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
9740 
9741   // I think we only want to look through implicit casts here; if the
9742   // user has an explicit widening cast, we should treat the value as
9743   // being of the new, wider type.
9744   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
9745     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
9746       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
9747 
9748     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
9749 
9750     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
9751                          CE->getCastKind() == CK_BooleanToSignedIntegral;
9752 
9753     // Assume that non-integer casts can span the full range of the type.
9754     if (!isIntegerCast)
9755       return OutputTypeRange;
9756 
9757     IntRange SubRange
9758       = GetExprRange(C, CE->getSubExpr(),
9759                      std::min(MaxWidth, OutputTypeRange.Width));
9760 
9761     // Bail out if the subexpr's range is as wide as the cast type.
9762     if (SubRange.Width >= OutputTypeRange.Width)
9763       return OutputTypeRange;
9764 
9765     // Otherwise, we take the smaller width, and we're non-negative if
9766     // either the output type or the subexpr is.
9767     return IntRange(SubRange.Width,
9768                     SubRange.NonNegative || OutputTypeRange.NonNegative);
9769   }
9770 
9771   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
9772     // If we can fold the condition, just take that operand.
9773     bool CondResult;
9774     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
9775       return GetExprRange(C, CondResult ? CO->getTrueExpr()
9776                                         : CO->getFalseExpr(),
9777                           MaxWidth);
9778 
9779     // Otherwise, conservatively merge.
9780     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
9781     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
9782     return IntRange::join(L, R);
9783   }
9784 
9785   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
9786     switch (BO->getOpcode()) {
9787     case BO_Cmp:
9788       llvm_unreachable("builtin <=> should have class type");
9789 
9790     // Boolean-valued operations are single-bit and positive.
9791     case BO_LAnd:
9792     case BO_LOr:
9793     case BO_LT:
9794     case BO_GT:
9795     case BO_LE:
9796     case BO_GE:
9797     case BO_EQ:
9798     case BO_NE:
9799       return IntRange::forBoolType();
9800 
9801     // The type of the assignments is the type of the LHS, so the RHS
9802     // is not necessarily the same type.
9803     case BO_MulAssign:
9804     case BO_DivAssign:
9805     case BO_RemAssign:
9806     case BO_AddAssign:
9807     case BO_SubAssign:
9808     case BO_XorAssign:
9809     case BO_OrAssign:
9810       // TODO: bitfields?
9811       return IntRange::forValueOfType(C, GetExprType(E));
9812 
9813     // Simple assignments just pass through the RHS, which will have
9814     // been coerced to the LHS type.
9815     case BO_Assign:
9816       // TODO: bitfields?
9817       return GetExprRange(C, BO->getRHS(), MaxWidth);
9818 
9819     // Operations with opaque sources are black-listed.
9820     case BO_PtrMemD:
9821     case BO_PtrMemI:
9822       return IntRange::forValueOfType(C, GetExprType(E));
9823 
9824     // Bitwise-and uses the *infinum* of the two source ranges.
9825     case BO_And:
9826     case BO_AndAssign:
9827       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
9828                             GetExprRange(C, BO->getRHS(), MaxWidth));
9829 
9830     // Left shift gets black-listed based on a judgement call.
9831     case BO_Shl:
9832       // ...except that we want to treat '1 << (blah)' as logically
9833       // positive.  It's an important idiom.
9834       if (IntegerLiteral *I
9835             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
9836         if (I->getValue() == 1) {
9837           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
9838           return IntRange(R.Width, /*NonNegative*/ true);
9839         }
9840       }
9841       LLVM_FALLTHROUGH;
9842 
9843     case BO_ShlAssign:
9844       return IntRange::forValueOfType(C, GetExprType(E));
9845 
9846     // Right shift by a constant can narrow its left argument.
9847     case BO_Shr:
9848     case BO_ShrAssign: {
9849       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9850 
9851       // If the shift amount is a positive constant, drop the width by
9852       // that much.
9853       llvm::APSInt shift;
9854       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
9855           shift.isNonNegative()) {
9856         unsigned zext = shift.getZExtValue();
9857         if (zext >= L.Width)
9858           L.Width = (L.NonNegative ? 0 : 1);
9859         else
9860           L.Width -= zext;
9861       }
9862 
9863       return L;
9864     }
9865 
9866     // Comma acts as its right operand.
9867     case BO_Comma:
9868       return GetExprRange(C, BO->getRHS(), MaxWidth);
9869 
9870     // Black-list pointer subtractions.
9871     case BO_Sub:
9872       if (BO->getLHS()->getType()->isPointerType())
9873         return IntRange::forValueOfType(C, GetExprType(E));
9874       break;
9875 
9876     // The width of a division result is mostly determined by the size
9877     // of the LHS.
9878     case BO_Div: {
9879       // Don't 'pre-truncate' the operands.
9880       unsigned opWidth = C.getIntWidth(GetExprType(E));
9881       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9882 
9883       // If the divisor is constant, use that.
9884       llvm::APSInt divisor;
9885       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
9886         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
9887         if (log2 >= L.Width)
9888           L.Width = (L.NonNegative ? 0 : 1);
9889         else
9890           L.Width = std::min(L.Width - log2, MaxWidth);
9891         return L;
9892       }
9893 
9894       // Otherwise, just use the LHS's width.
9895       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9896       return IntRange(L.Width, L.NonNegative && R.NonNegative);
9897     }
9898 
9899     // The result of a remainder can't be larger than the result of
9900     // either side.
9901     case BO_Rem: {
9902       // Don't 'pre-truncate' the operands.
9903       unsigned opWidth = C.getIntWidth(GetExprType(E));
9904       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
9905       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
9906 
9907       IntRange meet = IntRange::meet(L, R);
9908       meet.Width = std::min(meet.Width, MaxWidth);
9909       return meet;
9910     }
9911 
9912     // The default behavior is okay for these.
9913     case BO_Mul:
9914     case BO_Add:
9915     case BO_Xor:
9916     case BO_Or:
9917       break;
9918     }
9919 
9920     // The default case is to treat the operation as if it were closed
9921     // on the narrowest type that encompasses both operands.
9922     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
9923     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
9924     return IntRange::join(L, R);
9925   }
9926 
9927   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
9928     switch (UO->getOpcode()) {
9929     // Boolean-valued operations are white-listed.
9930     case UO_LNot:
9931       return IntRange::forBoolType();
9932 
9933     // Operations with opaque sources are black-listed.
9934     case UO_Deref:
9935     case UO_AddrOf: // should be impossible
9936       return IntRange::forValueOfType(C, GetExprType(E));
9937 
9938     default:
9939       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
9940     }
9941   }
9942 
9943   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
9944     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
9945 
9946   if (const auto *BitField = E->getSourceBitField())
9947     return IntRange(BitField->getBitWidthValue(C),
9948                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
9949 
9950   return IntRange::forValueOfType(C, GetExprType(E));
9951 }
9952 
9953 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
9954   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
9955 }
9956 
9957 /// Checks whether the given value, which currently has the given
9958 /// source semantics, has the same value when coerced through the
9959 /// target semantics.
9960 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
9961                                  const llvm::fltSemantics &Src,
9962                                  const llvm::fltSemantics &Tgt) {
9963   llvm::APFloat truncated = value;
9964 
9965   bool ignored;
9966   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
9967   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
9968 
9969   return truncated.bitwiseIsEqual(value);
9970 }
9971 
9972 /// Checks whether the given value, which currently has the given
9973 /// source semantics, has the same value when coerced through the
9974 /// target semantics.
9975 ///
9976 /// The value might be a vector of floats (or a complex number).
9977 static bool IsSameFloatAfterCast(const APValue &value,
9978                                  const llvm::fltSemantics &Src,
9979                                  const llvm::fltSemantics &Tgt) {
9980   if (value.isFloat())
9981     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
9982 
9983   if (value.isVector()) {
9984     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
9985       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
9986         return false;
9987     return true;
9988   }
9989 
9990   assert(value.isComplexFloat());
9991   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
9992           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
9993 }
9994 
9995 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
9996 
9997 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
9998   // Suppress cases where we are comparing against an enum constant.
9999   if (const DeclRefExpr *DR =
10000       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10001     if (isa<EnumConstantDecl>(DR->getDecl()))
10002       return true;
10003 
10004   // Suppress cases where the '0' value is expanded from a macro.
10005   if (E->getBeginLoc().isMacroID())
10006     return true;
10007 
10008   return false;
10009 }
10010 
10011 static bool isKnownToHaveUnsignedValue(Expr *E) {
10012   return E->getType()->isIntegerType() &&
10013          (!E->getType()->isSignedIntegerType() ||
10014           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10015 }
10016 
10017 namespace {
10018 /// The promoted range of values of a type. In general this has the
10019 /// following structure:
10020 ///
10021 ///     |-----------| . . . |-----------|
10022 ///     ^           ^       ^           ^
10023 ///    Min       HoleMin  HoleMax      Max
10024 ///
10025 /// ... where there is only a hole if a signed type is promoted to unsigned
10026 /// (in which case Min and Max are the smallest and largest representable
10027 /// values).
10028 struct PromotedRange {
10029   // Min, or HoleMax if there is a hole.
10030   llvm::APSInt PromotedMin;
10031   // Max, or HoleMin if there is a hole.
10032   llvm::APSInt PromotedMax;
10033 
10034   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10035     if (R.Width == 0)
10036       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10037     else if (R.Width >= BitWidth && !Unsigned) {
10038       // Promotion made the type *narrower*. This happens when promoting
10039       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10040       // Treat all values of 'signed int' as being in range for now.
10041       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10042       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10043     } else {
10044       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10045                         .extOrTrunc(BitWidth);
10046       PromotedMin.setIsUnsigned(Unsigned);
10047 
10048       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10049                         .extOrTrunc(BitWidth);
10050       PromotedMax.setIsUnsigned(Unsigned);
10051     }
10052   }
10053 
10054   // Determine whether this range is contiguous (has no hole).
10055   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10056 
10057   // Where a constant value is within the range.
10058   enum ComparisonResult {
10059     LT = 0x1,
10060     LE = 0x2,
10061     GT = 0x4,
10062     GE = 0x8,
10063     EQ = 0x10,
10064     NE = 0x20,
10065     InRangeFlag = 0x40,
10066 
10067     Less = LE | LT | NE,
10068     Min = LE | InRangeFlag,
10069     InRange = InRangeFlag,
10070     Max = GE | InRangeFlag,
10071     Greater = GE | GT | NE,
10072 
10073     OnlyValue = LE | GE | EQ | InRangeFlag,
10074     InHole = NE
10075   };
10076 
10077   ComparisonResult compare(const llvm::APSInt &Value) const {
10078     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10079            Value.isUnsigned() == PromotedMin.isUnsigned());
10080     if (!isContiguous()) {
10081       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10082       if (Value.isMinValue()) return Min;
10083       if (Value.isMaxValue()) return Max;
10084       if (Value >= PromotedMin) return InRange;
10085       if (Value <= PromotedMax) return InRange;
10086       return InHole;
10087     }
10088 
10089     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10090     case -1: return Less;
10091     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10092     case 1:
10093       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10094       case -1: return InRange;
10095       case 0: return Max;
10096       case 1: return Greater;
10097       }
10098     }
10099 
10100     llvm_unreachable("impossible compare result");
10101   }
10102 
10103   static llvm::Optional<StringRef>
10104   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
10105     if (Op == BO_Cmp) {
10106       ComparisonResult LTFlag = LT, GTFlag = GT;
10107       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
10108 
10109       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
10110       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
10111       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
10112       return llvm::None;
10113     }
10114 
10115     ComparisonResult TrueFlag, FalseFlag;
10116     if (Op == BO_EQ) {
10117       TrueFlag = EQ;
10118       FalseFlag = NE;
10119     } else if (Op == BO_NE) {
10120       TrueFlag = NE;
10121       FalseFlag = EQ;
10122     } else {
10123       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
10124         TrueFlag = LT;
10125         FalseFlag = GE;
10126       } else {
10127         TrueFlag = GT;
10128         FalseFlag = LE;
10129       }
10130       if (Op == BO_GE || Op == BO_LE)
10131         std::swap(TrueFlag, FalseFlag);
10132     }
10133     if (R & TrueFlag)
10134       return StringRef("true");
10135     if (R & FalseFlag)
10136       return StringRef("false");
10137     return llvm::None;
10138   }
10139 };
10140 }
10141 
10142 static bool HasEnumType(Expr *E) {
10143   // Strip off implicit integral promotions.
10144   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
10145     if (ICE->getCastKind() != CK_IntegralCast &&
10146         ICE->getCastKind() != CK_NoOp)
10147       break;
10148     E = ICE->getSubExpr();
10149   }
10150 
10151   return E->getType()->isEnumeralType();
10152 }
10153 
10154 static int classifyConstantValue(Expr *Constant) {
10155   // The values of this enumeration are used in the diagnostics
10156   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
10157   enum ConstantValueKind {
10158     Miscellaneous = 0,
10159     LiteralTrue,
10160     LiteralFalse
10161   };
10162   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
10163     return BL->getValue() ? ConstantValueKind::LiteralTrue
10164                           : ConstantValueKind::LiteralFalse;
10165   return ConstantValueKind::Miscellaneous;
10166 }
10167 
10168 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
10169                                         Expr *Constant, Expr *Other,
10170                                         const llvm::APSInt &Value,
10171                                         bool RhsConstant) {
10172   if (S.inTemplateInstantiation())
10173     return false;
10174 
10175   Expr *OriginalOther = Other;
10176 
10177   Constant = Constant->IgnoreParenImpCasts();
10178   Other = Other->IgnoreParenImpCasts();
10179 
10180   // Suppress warnings on tautological comparisons between values of the same
10181   // enumeration type. There are only two ways we could warn on this:
10182   //  - If the constant is outside the range of representable values of
10183   //    the enumeration. In such a case, we should warn about the cast
10184   //    to enumeration type, not about the comparison.
10185   //  - If the constant is the maximum / minimum in-range value. For an
10186   //    enumeratin type, such comparisons can be meaningful and useful.
10187   if (Constant->getType()->isEnumeralType() &&
10188       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
10189     return false;
10190 
10191   // TODO: Investigate using GetExprRange() to get tighter bounds
10192   // on the bit ranges.
10193   QualType OtherT = Other->getType();
10194   if (const auto *AT = OtherT->getAs<AtomicType>())
10195     OtherT = AT->getValueType();
10196   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
10197 
10198   // Whether we're treating Other as being a bool because of the form of
10199   // expression despite it having another type (typically 'int' in C).
10200   bool OtherIsBooleanDespiteType =
10201       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
10202   if (OtherIsBooleanDespiteType)
10203     OtherRange = IntRange::forBoolType();
10204 
10205   // Determine the promoted range of the other type and see if a comparison of
10206   // the constant against that range is tautological.
10207   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
10208                                    Value.isUnsigned());
10209   auto Cmp = OtherPromotedRange.compare(Value);
10210   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
10211   if (!Result)
10212     return false;
10213 
10214   // Suppress the diagnostic for an in-range comparison if the constant comes
10215   // from a macro or enumerator. We don't want to diagnose
10216   //
10217   //   some_long_value <= INT_MAX
10218   //
10219   // when sizeof(int) == sizeof(long).
10220   bool InRange = Cmp & PromotedRange::InRangeFlag;
10221   if (InRange && IsEnumConstOrFromMacro(S, Constant))
10222     return false;
10223 
10224   // If this is a comparison to an enum constant, include that
10225   // constant in the diagnostic.
10226   const EnumConstantDecl *ED = nullptr;
10227   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
10228     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
10229 
10230   // Should be enough for uint128 (39 decimal digits)
10231   SmallString<64> PrettySourceValue;
10232   llvm::raw_svector_ostream OS(PrettySourceValue);
10233   if (ED)
10234     OS << '\'' << *ED << "' (" << Value << ")";
10235   else
10236     OS << Value;
10237 
10238   // FIXME: We use a somewhat different formatting for the in-range cases and
10239   // cases involving boolean values for historical reasons. We should pick a
10240   // consistent way of presenting these diagnostics.
10241   if (!InRange || Other->isKnownToHaveBooleanValue()) {
10242     S.DiagRuntimeBehavior(
10243       E->getOperatorLoc(), E,
10244       S.PDiag(!InRange ? diag::warn_out_of_range_compare
10245                        : diag::warn_tautological_bool_compare)
10246           << OS.str() << classifyConstantValue(Constant)
10247           << OtherT << OtherIsBooleanDespiteType << *Result
10248           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
10249   } else {
10250     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
10251                         ? (HasEnumType(OriginalOther)
10252                                ? diag::warn_unsigned_enum_always_true_comparison
10253                                : diag::warn_unsigned_always_true_comparison)
10254                         : diag::warn_tautological_constant_compare;
10255 
10256     S.Diag(E->getOperatorLoc(), Diag)
10257         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
10258         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
10259   }
10260 
10261   return true;
10262 }
10263 
10264 /// Analyze the operands of the given comparison.  Implements the
10265 /// fallback case from AnalyzeComparison.
10266 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
10267   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10268   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10269 }
10270 
10271 /// Implements -Wsign-compare.
10272 ///
10273 /// \param E the binary operator to check for warnings
10274 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
10275   // The type the comparison is being performed in.
10276   QualType T = E->getLHS()->getType();
10277 
10278   // Only analyze comparison operators where both sides have been converted to
10279   // the same type.
10280   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
10281     return AnalyzeImpConvsInComparison(S, E);
10282 
10283   // Don't analyze value-dependent comparisons directly.
10284   if (E->isValueDependent())
10285     return AnalyzeImpConvsInComparison(S, E);
10286 
10287   Expr *LHS = E->getLHS();
10288   Expr *RHS = E->getRHS();
10289 
10290   if (T->isIntegralType(S.Context)) {
10291     llvm::APSInt RHSValue;
10292     llvm::APSInt LHSValue;
10293 
10294     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
10295     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
10296 
10297     // We don't care about expressions whose result is a constant.
10298     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
10299       return AnalyzeImpConvsInComparison(S, E);
10300 
10301     // We only care about expressions where just one side is literal
10302     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
10303       // Is the constant on the RHS or LHS?
10304       const bool RhsConstant = IsRHSIntegralLiteral;
10305       Expr *Const = RhsConstant ? RHS : LHS;
10306       Expr *Other = RhsConstant ? LHS : RHS;
10307       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
10308 
10309       // Check whether an integer constant comparison results in a value
10310       // of 'true' or 'false'.
10311       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
10312         return AnalyzeImpConvsInComparison(S, E);
10313     }
10314   }
10315 
10316   if (!T->hasUnsignedIntegerRepresentation()) {
10317     // We don't do anything special if this isn't an unsigned integral
10318     // comparison:  we're only interested in integral comparisons, and
10319     // signed comparisons only happen in cases we don't care to warn about.
10320     return AnalyzeImpConvsInComparison(S, E);
10321   }
10322 
10323   LHS = LHS->IgnoreParenImpCasts();
10324   RHS = RHS->IgnoreParenImpCasts();
10325 
10326   if (!S.getLangOpts().CPlusPlus) {
10327     // Avoid warning about comparison of integers with different signs when
10328     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
10329     // the type of `E`.
10330     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
10331       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10332     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
10333       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
10334   }
10335 
10336   // Check to see if one of the (unmodified) operands is of different
10337   // signedness.
10338   Expr *signedOperand, *unsignedOperand;
10339   if (LHS->getType()->hasSignedIntegerRepresentation()) {
10340     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
10341            "unsigned comparison between two signed integer expressions?");
10342     signedOperand = LHS;
10343     unsignedOperand = RHS;
10344   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
10345     signedOperand = RHS;
10346     unsignedOperand = LHS;
10347   } else {
10348     return AnalyzeImpConvsInComparison(S, E);
10349   }
10350 
10351   // Otherwise, calculate the effective range of the signed operand.
10352   IntRange signedRange = GetExprRange(S.Context, signedOperand);
10353 
10354   // Go ahead and analyze implicit conversions in the operands.  Note
10355   // that we skip the implicit conversions on both sides.
10356   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
10357   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
10358 
10359   // If the signed range is non-negative, -Wsign-compare won't fire.
10360   if (signedRange.NonNegative)
10361     return;
10362 
10363   // For (in)equality comparisons, if the unsigned operand is a
10364   // constant which cannot collide with a overflowed signed operand,
10365   // then reinterpreting the signed operand as unsigned will not
10366   // change the result of the comparison.
10367   if (E->isEqualityOp()) {
10368     unsigned comparisonWidth = S.Context.getIntWidth(T);
10369     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
10370 
10371     // We should never be unable to prove that the unsigned operand is
10372     // non-negative.
10373     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
10374 
10375     if (unsignedRange.Width < comparisonWidth)
10376       return;
10377   }
10378 
10379   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
10380     S.PDiag(diag::warn_mixed_sign_comparison)
10381       << LHS->getType() << RHS->getType()
10382       << LHS->getSourceRange() << RHS->getSourceRange());
10383 }
10384 
10385 /// Analyzes an attempt to assign the given value to a bitfield.
10386 ///
10387 /// Returns true if there was something fishy about the attempt.
10388 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
10389                                       SourceLocation InitLoc) {
10390   assert(Bitfield->isBitField());
10391   if (Bitfield->isInvalidDecl())
10392     return false;
10393 
10394   // White-list bool bitfields.
10395   QualType BitfieldType = Bitfield->getType();
10396   if (BitfieldType->isBooleanType())
10397      return false;
10398 
10399   if (BitfieldType->isEnumeralType()) {
10400     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
10401     // If the underlying enum type was not explicitly specified as an unsigned
10402     // type and the enum contain only positive values, MSVC++ will cause an
10403     // inconsistency by storing this as a signed type.
10404     if (S.getLangOpts().CPlusPlus11 &&
10405         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
10406         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
10407         BitfieldEnumDecl->getNumNegativeBits() == 0) {
10408       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
10409         << BitfieldEnumDecl->getNameAsString();
10410     }
10411   }
10412 
10413   if (Bitfield->getType()->isBooleanType())
10414     return false;
10415 
10416   // Ignore value- or type-dependent expressions.
10417   if (Bitfield->getBitWidth()->isValueDependent() ||
10418       Bitfield->getBitWidth()->isTypeDependent() ||
10419       Init->isValueDependent() ||
10420       Init->isTypeDependent())
10421     return false;
10422 
10423   Expr *OriginalInit = Init->IgnoreParenImpCasts();
10424   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
10425 
10426   Expr::EvalResult Result;
10427   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
10428                                    Expr::SE_AllowSideEffects)) {
10429     // The RHS is not constant.  If the RHS has an enum type, make sure the
10430     // bitfield is wide enough to hold all the values of the enum without
10431     // truncation.
10432     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
10433       EnumDecl *ED = EnumTy->getDecl();
10434       bool SignedBitfield = BitfieldType->isSignedIntegerType();
10435 
10436       // Enum types are implicitly signed on Windows, so check if there are any
10437       // negative enumerators to see if the enum was intended to be signed or
10438       // not.
10439       bool SignedEnum = ED->getNumNegativeBits() > 0;
10440 
10441       // Check for surprising sign changes when assigning enum values to a
10442       // bitfield of different signedness.  If the bitfield is signed and we
10443       // have exactly the right number of bits to store this unsigned enum,
10444       // suggest changing the enum to an unsigned type. This typically happens
10445       // on Windows where unfixed enums always use an underlying type of 'int'.
10446       unsigned DiagID = 0;
10447       if (SignedEnum && !SignedBitfield) {
10448         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
10449       } else if (SignedBitfield && !SignedEnum &&
10450                  ED->getNumPositiveBits() == FieldWidth) {
10451         DiagID = diag::warn_signed_bitfield_enum_conversion;
10452       }
10453 
10454       if (DiagID) {
10455         S.Diag(InitLoc, DiagID) << Bitfield << ED;
10456         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
10457         SourceRange TypeRange =
10458             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
10459         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
10460             << SignedEnum << TypeRange;
10461       }
10462 
10463       // Compute the required bitwidth. If the enum has negative values, we need
10464       // one more bit than the normal number of positive bits to represent the
10465       // sign bit.
10466       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
10467                                                   ED->getNumNegativeBits())
10468                                        : ED->getNumPositiveBits();
10469 
10470       // Check the bitwidth.
10471       if (BitsNeeded > FieldWidth) {
10472         Expr *WidthExpr = Bitfield->getBitWidth();
10473         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
10474             << Bitfield << ED;
10475         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
10476             << BitsNeeded << ED << WidthExpr->getSourceRange();
10477       }
10478     }
10479 
10480     return false;
10481   }
10482 
10483   llvm::APSInt Value = Result.Val.getInt();
10484 
10485   unsigned OriginalWidth = Value.getBitWidth();
10486 
10487   if (!Value.isSigned() || Value.isNegative())
10488     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
10489       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
10490         OriginalWidth = Value.getMinSignedBits();
10491 
10492   if (OriginalWidth <= FieldWidth)
10493     return false;
10494 
10495   // Compute the value which the bitfield will contain.
10496   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
10497   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
10498 
10499   // Check whether the stored value is equal to the original value.
10500   TruncatedValue = TruncatedValue.extend(OriginalWidth);
10501   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
10502     return false;
10503 
10504   // Special-case bitfields of width 1: booleans are naturally 0/1, and
10505   // therefore don't strictly fit into a signed bitfield of width 1.
10506   if (FieldWidth == 1 && Value == 1)
10507     return false;
10508 
10509   std::string PrettyValue = Value.toString(10);
10510   std::string PrettyTrunc = TruncatedValue.toString(10);
10511 
10512   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
10513     << PrettyValue << PrettyTrunc << OriginalInit->getType()
10514     << Init->getSourceRange();
10515 
10516   return true;
10517 }
10518 
10519 /// Analyze the given simple or compound assignment for warning-worthy
10520 /// operations.
10521 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
10522   // Just recurse on the LHS.
10523   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10524 
10525   // We want to recurse on the RHS as normal unless we're assigning to
10526   // a bitfield.
10527   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
10528     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
10529                                   E->getOperatorLoc())) {
10530       // Recurse, ignoring any implicit conversions on the RHS.
10531       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
10532                                         E->getOperatorLoc());
10533     }
10534   }
10535 
10536   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10537 
10538   // Diagnose implicitly sequentially-consistent atomic assignment.
10539   if (E->getLHS()->getType()->isAtomicType())
10540     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
10541 }
10542 
10543 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10544 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
10545                             SourceLocation CContext, unsigned diag,
10546                             bool pruneControlFlow = false) {
10547   if (pruneControlFlow) {
10548     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10549                           S.PDiag(diag)
10550                             << SourceType << T << E->getSourceRange()
10551                             << SourceRange(CContext));
10552     return;
10553   }
10554   S.Diag(E->getExprLoc(), diag)
10555     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
10556 }
10557 
10558 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
10559 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
10560                             SourceLocation CContext,
10561                             unsigned diag, bool pruneControlFlow = false) {
10562   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
10563 }
10564 
10565 /// Diagnose an implicit cast from a floating point value to an integer value.
10566 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
10567                                     SourceLocation CContext) {
10568   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
10569   const bool PruneWarnings = S.inTemplateInstantiation();
10570 
10571   Expr *InnerE = E->IgnoreParenImpCasts();
10572   // We also want to warn on, e.g., "int i = -1.234"
10573   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
10574     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
10575       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
10576 
10577   const bool IsLiteral =
10578       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
10579 
10580   llvm::APFloat Value(0.0);
10581   bool IsConstant =
10582     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
10583   if (!IsConstant) {
10584     return DiagnoseImpCast(S, E, T, CContext,
10585                            diag::warn_impcast_float_integer, PruneWarnings);
10586   }
10587 
10588   bool isExact = false;
10589 
10590   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
10591                             T->hasUnsignedIntegerRepresentation());
10592   llvm::APFloat::opStatus Result = Value.convertToInteger(
10593       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
10594 
10595   if (Result == llvm::APFloat::opOK && isExact) {
10596     if (IsLiteral) return;
10597     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
10598                            PruneWarnings);
10599   }
10600 
10601   // Conversion of a floating-point value to a non-bool integer where the
10602   // integral part cannot be represented by the integer type is undefined.
10603   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
10604     return DiagnoseImpCast(
10605         S, E, T, CContext,
10606         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
10607                   : diag::warn_impcast_float_to_integer_out_of_range,
10608         PruneWarnings);
10609 
10610   unsigned DiagID = 0;
10611   if (IsLiteral) {
10612     // Warn on floating point literal to integer.
10613     DiagID = diag::warn_impcast_literal_float_to_integer;
10614   } else if (IntegerValue == 0) {
10615     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
10616       return DiagnoseImpCast(S, E, T, CContext,
10617                              diag::warn_impcast_float_integer, PruneWarnings);
10618     }
10619     // Warn on non-zero to zero conversion.
10620     DiagID = diag::warn_impcast_float_to_integer_zero;
10621   } else {
10622     if (IntegerValue.isUnsigned()) {
10623       if (!IntegerValue.isMaxValue()) {
10624         return DiagnoseImpCast(S, E, T, CContext,
10625                                diag::warn_impcast_float_integer, PruneWarnings);
10626       }
10627     } else {  // IntegerValue.isSigned()
10628       if (!IntegerValue.isMaxSignedValue() &&
10629           !IntegerValue.isMinSignedValue()) {
10630         return DiagnoseImpCast(S, E, T, CContext,
10631                                diag::warn_impcast_float_integer, PruneWarnings);
10632       }
10633     }
10634     // Warn on evaluatable floating point expression to integer conversion.
10635     DiagID = diag::warn_impcast_float_to_integer;
10636   }
10637 
10638   // FIXME: Force the precision of the source value down so we don't print
10639   // digits which are usually useless (we don't really care here if we
10640   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
10641   // would automatically print the shortest representation, but it's a bit
10642   // tricky to implement.
10643   SmallString<16> PrettySourceValue;
10644   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
10645   precision = (precision * 59 + 195) / 196;
10646   Value.toString(PrettySourceValue, precision);
10647 
10648   SmallString<16> PrettyTargetValue;
10649   if (IsBool)
10650     PrettyTargetValue = Value.isZero() ? "false" : "true";
10651   else
10652     IntegerValue.toString(PrettyTargetValue);
10653 
10654   if (PruneWarnings) {
10655     S.DiagRuntimeBehavior(E->getExprLoc(), E,
10656                           S.PDiag(DiagID)
10657                               << E->getType() << T.getUnqualifiedType()
10658                               << PrettySourceValue << PrettyTargetValue
10659                               << E->getSourceRange() << SourceRange(CContext));
10660   } else {
10661     S.Diag(E->getExprLoc(), DiagID)
10662         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
10663         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
10664   }
10665 }
10666 
10667 /// Analyze the given compound assignment for the possible losing of
10668 /// floating-point precision.
10669 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
10670   assert(isa<CompoundAssignOperator>(E) &&
10671          "Must be compound assignment operation");
10672   // Recurse on the LHS and RHS in here
10673   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
10674   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
10675 
10676   if (E->getLHS()->getType()->isAtomicType())
10677     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
10678 
10679   // Now check the outermost expression
10680   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
10681   const auto *RBT = cast<CompoundAssignOperator>(E)
10682                         ->getComputationResultType()
10683                         ->getAs<BuiltinType>();
10684 
10685   // The below checks assume source is floating point.
10686   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
10687 
10688   // If source is floating point but target is an integer.
10689   if (ResultBT->isInteger())
10690     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
10691                            E->getExprLoc(), diag::warn_impcast_float_integer);
10692 
10693   if (!ResultBT->isFloatingPoint())
10694     return;
10695 
10696   // If both source and target are floating points, warn about losing precision.
10697   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
10698       QualType(ResultBT, 0), QualType(RBT, 0));
10699   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
10700     // warn about dropping FP rank.
10701     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
10702                     diag::warn_impcast_float_result_precision);
10703 }
10704 
10705 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
10706                                       IntRange Range) {
10707   if (!Range.Width) return "0";
10708 
10709   llvm::APSInt ValueInRange = Value;
10710   ValueInRange.setIsSigned(!Range.NonNegative);
10711   ValueInRange = ValueInRange.trunc(Range.Width);
10712   return ValueInRange.toString(10);
10713 }
10714 
10715 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
10716   if (!isa<ImplicitCastExpr>(Ex))
10717     return false;
10718 
10719   Expr *InnerE = Ex->IgnoreParenImpCasts();
10720   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
10721   const Type *Source =
10722     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
10723   if (Target->isDependentType())
10724     return false;
10725 
10726   const BuiltinType *FloatCandidateBT =
10727     dyn_cast<BuiltinType>(ToBool ? Source : Target);
10728   const Type *BoolCandidateType = ToBool ? Target : Source;
10729 
10730   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
10731           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
10732 }
10733 
10734 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
10735                                              SourceLocation CC) {
10736   unsigned NumArgs = TheCall->getNumArgs();
10737   for (unsigned i = 0; i < NumArgs; ++i) {
10738     Expr *CurrA = TheCall->getArg(i);
10739     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
10740       continue;
10741 
10742     bool IsSwapped = ((i > 0) &&
10743         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
10744     IsSwapped |= ((i < (NumArgs - 1)) &&
10745         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
10746     if (IsSwapped) {
10747       // Warn on this floating-point to bool conversion.
10748       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
10749                       CurrA->getType(), CC,
10750                       diag::warn_impcast_floating_point_to_bool);
10751     }
10752   }
10753 }
10754 
10755 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
10756                                    SourceLocation CC) {
10757   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
10758                         E->getExprLoc()))
10759     return;
10760 
10761   // Don't warn on functions which have return type nullptr_t.
10762   if (isa<CallExpr>(E))
10763     return;
10764 
10765   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
10766   const Expr::NullPointerConstantKind NullKind =
10767       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
10768   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
10769     return;
10770 
10771   // Return if target type is a safe conversion.
10772   if (T->isAnyPointerType() || T->isBlockPointerType() ||
10773       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
10774     return;
10775 
10776   SourceLocation Loc = E->getSourceRange().getBegin();
10777 
10778   // Venture through the macro stacks to get to the source of macro arguments.
10779   // The new location is a better location than the complete location that was
10780   // passed in.
10781   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
10782   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
10783 
10784   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
10785   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
10786     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
10787         Loc, S.SourceMgr, S.getLangOpts());
10788     if (MacroName == "NULL")
10789       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
10790   }
10791 
10792   // Only warn if the null and context location are in the same macro expansion.
10793   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
10794     return;
10795 
10796   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
10797       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
10798       << FixItHint::CreateReplacement(Loc,
10799                                       S.getFixItZeroLiteralForType(T, Loc));
10800 }
10801 
10802 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10803                                   ObjCArrayLiteral *ArrayLiteral);
10804 
10805 static void
10806 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10807                            ObjCDictionaryLiteral *DictionaryLiteral);
10808 
10809 /// Check a single element within a collection literal against the
10810 /// target element type.
10811 static void checkObjCCollectionLiteralElement(Sema &S,
10812                                               QualType TargetElementType,
10813                                               Expr *Element,
10814                                               unsigned ElementKind) {
10815   // Skip a bitcast to 'id' or qualified 'id'.
10816   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
10817     if (ICE->getCastKind() == CK_BitCast &&
10818         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
10819       Element = ICE->getSubExpr();
10820   }
10821 
10822   QualType ElementType = Element->getType();
10823   ExprResult ElementResult(Element);
10824   if (ElementType->getAs<ObjCObjectPointerType>() &&
10825       S.CheckSingleAssignmentConstraints(TargetElementType,
10826                                          ElementResult,
10827                                          false, false)
10828         != Sema::Compatible) {
10829     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
10830         << ElementType << ElementKind << TargetElementType
10831         << Element->getSourceRange();
10832   }
10833 
10834   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
10835     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
10836   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
10837     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
10838 }
10839 
10840 /// Check an Objective-C array literal being converted to the given
10841 /// target type.
10842 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
10843                                   ObjCArrayLiteral *ArrayLiteral) {
10844   if (!S.NSArrayDecl)
10845     return;
10846 
10847   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10848   if (!TargetObjCPtr)
10849     return;
10850 
10851   if (TargetObjCPtr->isUnspecialized() ||
10852       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10853         != S.NSArrayDecl->getCanonicalDecl())
10854     return;
10855 
10856   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10857   if (TypeArgs.size() != 1)
10858     return;
10859 
10860   QualType TargetElementType = TypeArgs[0];
10861   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
10862     checkObjCCollectionLiteralElement(S, TargetElementType,
10863                                       ArrayLiteral->getElement(I),
10864                                       0);
10865   }
10866 }
10867 
10868 /// Check an Objective-C dictionary literal being converted to the given
10869 /// target type.
10870 static void
10871 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
10872                            ObjCDictionaryLiteral *DictionaryLiteral) {
10873   if (!S.NSDictionaryDecl)
10874     return;
10875 
10876   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
10877   if (!TargetObjCPtr)
10878     return;
10879 
10880   if (TargetObjCPtr->isUnspecialized() ||
10881       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
10882         != S.NSDictionaryDecl->getCanonicalDecl())
10883     return;
10884 
10885   auto TypeArgs = TargetObjCPtr->getTypeArgs();
10886   if (TypeArgs.size() != 2)
10887     return;
10888 
10889   QualType TargetKeyType = TypeArgs[0];
10890   QualType TargetObjectType = TypeArgs[1];
10891   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
10892     auto Element = DictionaryLiteral->getKeyValueElement(I);
10893     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
10894     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
10895   }
10896 }
10897 
10898 // Helper function to filter out cases for constant width constant conversion.
10899 // Don't warn on char array initialization or for non-decimal values.
10900 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
10901                                           SourceLocation CC) {
10902   // If initializing from a constant, and the constant starts with '0',
10903   // then it is a binary, octal, or hexadecimal.  Allow these constants
10904   // to fill all the bits, even if there is a sign change.
10905   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
10906     const char FirstLiteralCharacter =
10907         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
10908     if (FirstLiteralCharacter == '0')
10909       return false;
10910   }
10911 
10912   // If the CC location points to a '{', and the type is char, then assume
10913   // assume it is an array initialization.
10914   if (CC.isValid() && T->isCharType()) {
10915     const char FirstContextCharacter =
10916         S.getSourceManager().getCharacterData(CC)[0];
10917     if (FirstContextCharacter == '{')
10918       return false;
10919   }
10920 
10921   return true;
10922 }
10923 
10924 static void
10925 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
10926                         bool *ICContext = nullptr) {
10927   if (E->isTypeDependent() || E->isValueDependent()) return;
10928 
10929   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
10930   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
10931   if (Source == Target) return;
10932   if (Target->isDependentType()) return;
10933 
10934   // If the conversion context location is invalid don't complain. We also
10935   // don't want to emit a warning if the issue occurs from the expansion of
10936   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
10937   // delay this check as long as possible. Once we detect we are in that
10938   // scenario, we just return.
10939   if (CC.isInvalid())
10940     return;
10941 
10942   if (Source->isAtomicType())
10943     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
10944 
10945   // Diagnose implicit casts to bool.
10946   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
10947     if (isa<StringLiteral>(E))
10948       // Warn on string literal to bool.  Checks for string literals in logical
10949       // and expressions, for instance, assert(0 && "error here"), are
10950       // prevented by a check in AnalyzeImplicitConversions().
10951       return DiagnoseImpCast(S, E, T, CC,
10952                              diag::warn_impcast_string_literal_to_bool);
10953     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
10954         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
10955       // This covers the literal expressions that evaluate to Objective-C
10956       // objects.
10957       return DiagnoseImpCast(S, E, T, CC,
10958                              diag::warn_impcast_objective_c_literal_to_bool);
10959     }
10960     if (Source->isPointerType() || Source->canDecayToPointerType()) {
10961       // Warn on pointer to bool conversion that is always true.
10962       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
10963                                      SourceRange(CC));
10964     }
10965   }
10966 
10967   // Check implicit casts from Objective-C collection literals to specialized
10968   // collection types, e.g., NSArray<NSString *> *.
10969   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
10970     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
10971   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
10972     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
10973 
10974   // Strip vector types.
10975   if (isa<VectorType>(Source)) {
10976     if (!isa<VectorType>(Target)) {
10977       if (S.SourceMgr.isInSystemMacro(CC))
10978         return;
10979       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
10980     }
10981 
10982     // If the vector cast is cast between two vectors of the same size, it is
10983     // a bitcast, not a conversion.
10984     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
10985       return;
10986 
10987     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
10988     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
10989   }
10990   if (auto VecTy = dyn_cast<VectorType>(Target))
10991     Target = VecTy->getElementType().getTypePtr();
10992 
10993   // Strip complex types.
10994   if (isa<ComplexType>(Source)) {
10995     if (!isa<ComplexType>(Target)) {
10996       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
10997         return;
10998 
10999       return DiagnoseImpCast(S, E, T, CC,
11000                              S.getLangOpts().CPlusPlus
11001                                  ? diag::err_impcast_complex_scalar
11002                                  : diag::warn_impcast_complex_scalar);
11003     }
11004 
11005     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
11006     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
11007   }
11008 
11009   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
11010   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
11011 
11012   // If the source is floating point...
11013   if (SourceBT && SourceBT->isFloatingPoint()) {
11014     // ...and the target is floating point...
11015     if (TargetBT && TargetBT->isFloatingPoint()) {
11016       // ...then warn if we're dropping FP rank.
11017 
11018       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11019           QualType(SourceBT, 0), QualType(TargetBT, 0));
11020       if (Order > 0) {
11021         // Don't warn about float constants that are precisely
11022         // representable in the target type.
11023         Expr::EvalResult result;
11024         if (E->EvaluateAsRValue(result, S.Context)) {
11025           // Value might be a float, a float vector, or a float complex.
11026           if (IsSameFloatAfterCast(result.Val,
11027                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
11028                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
11029             return;
11030         }
11031 
11032         if (S.SourceMgr.isInSystemMacro(CC))
11033           return;
11034 
11035         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
11036       }
11037       // ... or possibly if we're increasing rank, too
11038       else if (Order < 0) {
11039         if (S.SourceMgr.isInSystemMacro(CC))
11040           return;
11041 
11042         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
11043       }
11044       return;
11045     }
11046 
11047     // If the target is integral, always warn.
11048     if (TargetBT && TargetBT->isInteger()) {
11049       if (S.SourceMgr.isInSystemMacro(CC))
11050         return;
11051 
11052       DiagnoseFloatingImpCast(S, E, T, CC);
11053     }
11054 
11055     // Detect the case where a call result is converted from floating-point to
11056     // to bool, and the final argument to the call is converted from bool, to
11057     // discover this typo:
11058     //
11059     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
11060     //
11061     // FIXME: This is an incredibly special case; is there some more general
11062     // way to detect this class of misplaced-parentheses bug?
11063     if (Target->isBooleanType() && isa<CallExpr>(E)) {
11064       // Check last argument of function call to see if it is an
11065       // implicit cast from a type matching the type the result
11066       // is being cast to.
11067       CallExpr *CEx = cast<CallExpr>(E);
11068       if (unsigned NumArgs = CEx->getNumArgs()) {
11069         Expr *LastA = CEx->getArg(NumArgs - 1);
11070         Expr *InnerE = LastA->IgnoreParenImpCasts();
11071         if (isa<ImplicitCastExpr>(LastA) &&
11072             InnerE->getType()->isBooleanType()) {
11073           // Warn on this floating-point to bool conversion
11074           DiagnoseImpCast(S, E, T, CC,
11075                           diag::warn_impcast_floating_point_to_bool);
11076         }
11077       }
11078     }
11079     return;
11080   }
11081 
11082   // Valid casts involving fixed point types should be accounted for here.
11083   if (Source->isFixedPointType()) {
11084     if (Target->isUnsaturatedFixedPointType()) {
11085       Expr::EvalResult Result;
11086       if (E->EvaluateAsFixedPoint(Result, S.Context,
11087                                   Expr::SE_AllowSideEffects)) {
11088         APFixedPoint Value = Result.Val.getFixedPoint();
11089         APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
11090         APFixedPoint MinVal = S.Context.getFixedPointMin(T);
11091         if (Value > MaxVal || Value < MinVal) {
11092           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11093                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11094                                     << Value.toString() << T
11095                                     << E->getSourceRange()
11096                                     << clang::SourceRange(CC));
11097           return;
11098         }
11099       }
11100     } else if (Target->isIntegerType()) {
11101       Expr::EvalResult Result;
11102       if (E->EvaluateAsFixedPoint(Result, S.Context,
11103                                   Expr::SE_AllowSideEffects)) {
11104         APFixedPoint FXResult = Result.Val.getFixedPoint();
11105 
11106         bool Overflowed;
11107         llvm::APSInt IntResult = FXResult.convertToInt(
11108             S.Context.getIntWidth(T),
11109             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
11110 
11111         if (Overflowed) {
11112           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11113                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11114                                     << FXResult.toString() << T
11115                                     << E->getSourceRange()
11116                                     << clang::SourceRange(CC));
11117           return;
11118         }
11119       }
11120     }
11121   } else if (Target->isUnsaturatedFixedPointType()) {
11122     if (Source->isIntegerType()) {
11123       Expr::EvalResult Result;
11124       if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11125         llvm::APSInt Value = Result.Val.getInt();
11126 
11127         bool Overflowed;
11128         APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11129             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
11130 
11131         if (Overflowed) {
11132           S.DiagRuntimeBehavior(E->getExprLoc(), E,
11133                                 S.PDiag(diag::warn_impcast_fixed_point_range)
11134                                     << Value.toString(/*radix=*/10) << T
11135                                     << E->getSourceRange()
11136                                     << clang::SourceRange(CC));
11137           return;
11138         }
11139       }
11140     }
11141   }
11142 
11143   DiagnoseNullConversion(S, E, T, CC);
11144 
11145   S.DiscardMisalignedMemberAddress(Target, E);
11146 
11147   if (!Source->isIntegerType() || !Target->isIntegerType())
11148     return;
11149 
11150   // TODO: remove this early return once the false positives for constant->bool
11151   // in templates, macros, etc, are reduced or removed.
11152   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
11153     return;
11154 
11155   IntRange SourceRange = GetExprRange(S.Context, E);
11156   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
11157 
11158   if (SourceRange.Width > TargetRange.Width) {
11159     // If the source is a constant, use a default-on diagnostic.
11160     // TODO: this should happen for bitfield stores, too.
11161     Expr::EvalResult Result;
11162     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
11163       llvm::APSInt Value(32);
11164       Value = Result.Val.getInt();
11165 
11166       if (S.SourceMgr.isInSystemMacro(CC))
11167         return;
11168 
11169       std::string PrettySourceValue = Value.toString(10);
11170       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11171 
11172       S.DiagRuntimeBehavior(E->getExprLoc(), E,
11173         S.PDiag(diag::warn_impcast_integer_precision_constant)
11174             << PrettySourceValue << PrettyTargetValue
11175             << E->getType() << T << E->getSourceRange()
11176             << clang::SourceRange(CC));
11177       return;
11178     }
11179 
11180     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
11181     if (S.SourceMgr.isInSystemMacro(CC))
11182       return;
11183 
11184     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
11185       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
11186                              /* pruneControlFlow */ true);
11187     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
11188   }
11189 
11190   if (TargetRange.Width > SourceRange.Width) {
11191     if (auto *UO = dyn_cast<UnaryOperator>(E))
11192       if (UO->getOpcode() == UO_Minus)
11193         if (Source->isUnsignedIntegerType()) {
11194           if (Target->isUnsignedIntegerType())
11195             return DiagnoseImpCast(S, E, T, CC,
11196                                    diag::warn_impcast_high_order_zero_bits);
11197           if (Target->isSignedIntegerType())
11198             return DiagnoseImpCast(S, E, T, CC,
11199                                    diag::warn_impcast_nonnegative_result);
11200         }
11201   }
11202 
11203   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
11204       SourceRange.NonNegative && Source->isSignedIntegerType()) {
11205     // Warn when doing a signed to signed conversion, warn if the positive
11206     // source value is exactly the width of the target type, which will
11207     // cause a negative value to be stored.
11208 
11209     Expr::EvalResult Result;
11210     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
11211         !S.SourceMgr.isInSystemMacro(CC)) {
11212       llvm::APSInt Value = Result.Val.getInt();
11213       if (isSameWidthConstantConversion(S, E, T, CC)) {
11214         std::string PrettySourceValue = Value.toString(10);
11215         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
11216 
11217         S.DiagRuntimeBehavior(
11218             E->getExprLoc(), E,
11219             S.PDiag(diag::warn_impcast_integer_precision_constant)
11220                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
11221                 << E->getSourceRange() << clang::SourceRange(CC));
11222         return;
11223       }
11224     }
11225 
11226     // Fall through for non-constants to give a sign conversion warning.
11227   }
11228 
11229   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
11230       (!TargetRange.NonNegative && SourceRange.NonNegative &&
11231        SourceRange.Width == TargetRange.Width)) {
11232     if (S.SourceMgr.isInSystemMacro(CC))
11233       return;
11234 
11235     unsigned DiagID = diag::warn_impcast_integer_sign;
11236 
11237     // Traditionally, gcc has warned about this under -Wsign-compare.
11238     // We also want to warn about it in -Wconversion.
11239     // So if -Wconversion is off, use a completely identical diagnostic
11240     // in the sign-compare group.
11241     // The conditional-checking code will
11242     if (ICContext) {
11243       DiagID = diag::warn_impcast_integer_sign_conditional;
11244       *ICContext = true;
11245     }
11246 
11247     return DiagnoseImpCast(S, E, T, CC, DiagID);
11248   }
11249 
11250   // Diagnose conversions between different enumeration types.
11251   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
11252   // type, to give us better diagnostics.
11253   QualType SourceType = E->getType();
11254   if (!S.getLangOpts().CPlusPlus) {
11255     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11256       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
11257         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
11258         SourceType = S.Context.getTypeDeclType(Enum);
11259         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
11260       }
11261   }
11262 
11263   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
11264     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
11265       if (SourceEnum->getDecl()->hasNameForLinkage() &&
11266           TargetEnum->getDecl()->hasNameForLinkage() &&
11267           SourceEnum != TargetEnum) {
11268         if (S.SourceMgr.isInSystemMacro(CC))
11269           return;
11270 
11271         return DiagnoseImpCast(S, E, SourceType, T, CC,
11272                                diag::warn_impcast_different_enum_types);
11273       }
11274 }
11275 
11276 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11277                                      SourceLocation CC, QualType T);
11278 
11279 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
11280                                     SourceLocation CC, bool &ICContext) {
11281   E = E->IgnoreParenImpCasts();
11282 
11283   if (isa<ConditionalOperator>(E))
11284     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
11285 
11286   AnalyzeImplicitConversions(S, E, CC);
11287   if (E->getType() != T)
11288     return CheckImplicitConversion(S, E, T, CC, &ICContext);
11289 }
11290 
11291 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
11292                                      SourceLocation CC, QualType T) {
11293   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
11294 
11295   bool Suspicious = false;
11296   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
11297   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
11298 
11299   // If -Wconversion would have warned about either of the candidates
11300   // for a signedness conversion to the context type...
11301   if (!Suspicious) return;
11302 
11303   // ...but it's currently ignored...
11304   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
11305     return;
11306 
11307   // ...then check whether it would have warned about either of the
11308   // candidates for a signedness conversion to the condition type.
11309   if (E->getType() == T) return;
11310 
11311   Suspicious = false;
11312   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
11313                           E->getType(), CC, &Suspicious);
11314   if (!Suspicious)
11315     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
11316                             E->getType(), CC, &Suspicious);
11317 }
11318 
11319 /// Check conversion of given expression to boolean.
11320 /// Input argument E is a logical expression.
11321 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
11322   if (S.getLangOpts().Bool)
11323     return;
11324   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
11325     return;
11326   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
11327 }
11328 
11329 /// AnalyzeImplicitConversions - Find and report any interesting
11330 /// implicit conversions in the given expression.  There are a couple
11331 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
11332 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
11333                                        SourceLocation CC) {
11334   QualType T = OrigE->getType();
11335   Expr *E = OrigE->IgnoreParenImpCasts();
11336 
11337   if (E->isTypeDependent() || E->isValueDependent())
11338     return;
11339 
11340   // For conditional operators, we analyze the arguments as if they
11341   // were being fed directly into the output.
11342   if (isa<ConditionalOperator>(E)) {
11343     ConditionalOperator *CO = cast<ConditionalOperator>(E);
11344     CheckConditionalOperator(S, CO, CC, T);
11345     return;
11346   }
11347 
11348   // Check implicit argument conversions for function calls.
11349   if (CallExpr *Call = dyn_cast<CallExpr>(E))
11350     CheckImplicitArgumentConversions(S, Call, CC);
11351 
11352   // Go ahead and check any implicit conversions we might have skipped.
11353   // The non-canonical typecheck is just an optimization;
11354   // CheckImplicitConversion will filter out dead implicit conversions.
11355   if (E->getType() != T)
11356     CheckImplicitConversion(S, E, T, CC);
11357 
11358   // Now continue drilling into this expression.
11359 
11360   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
11361     // The bound subexpressions in a PseudoObjectExpr are not reachable
11362     // as transitive children.
11363     // FIXME: Use a more uniform representation for this.
11364     for (auto *SE : POE->semantics())
11365       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
11366         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
11367   }
11368 
11369   // Skip past explicit casts.
11370   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
11371     E = CE->getSubExpr()->IgnoreParenImpCasts();
11372     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
11373       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11374     return AnalyzeImplicitConversions(S, E, CC);
11375   }
11376 
11377   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11378     // Do a somewhat different check with comparison operators.
11379     if (BO->isComparisonOp())
11380       return AnalyzeComparison(S, BO);
11381 
11382     // And with simple assignments.
11383     if (BO->getOpcode() == BO_Assign)
11384       return AnalyzeAssignment(S, BO);
11385     // And with compound assignments.
11386     if (BO->isAssignmentOp())
11387       return AnalyzeCompoundAssignment(S, BO);
11388   }
11389 
11390   // These break the otherwise-useful invariant below.  Fortunately,
11391   // we don't really need to recurse into them, because any internal
11392   // expressions should have been analyzed already when they were
11393   // built into statements.
11394   if (isa<StmtExpr>(E)) return;
11395 
11396   // Don't descend into unevaluated contexts.
11397   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
11398 
11399   // Now just recurse over the expression's children.
11400   CC = E->getExprLoc();
11401   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
11402   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
11403   for (Stmt *SubStmt : E->children()) {
11404     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
11405     if (!ChildExpr)
11406       continue;
11407 
11408     if (IsLogicalAndOperator &&
11409         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
11410       // Ignore checking string literals that are in logical and operators.
11411       // This is a common pattern for asserts.
11412       continue;
11413     AnalyzeImplicitConversions(S, ChildExpr, CC);
11414   }
11415 
11416   if (BO && BO->isLogicalOp()) {
11417     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
11418     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11419       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11420 
11421     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
11422     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
11423       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
11424   }
11425 
11426   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
11427     if (U->getOpcode() == UO_LNot) {
11428       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
11429     } else if (U->getOpcode() != UO_AddrOf) {
11430       if (U->getSubExpr()->getType()->isAtomicType())
11431         S.Diag(U->getSubExpr()->getBeginLoc(),
11432                diag::warn_atomic_implicit_seq_cst);
11433     }
11434   }
11435 }
11436 
11437 /// Diagnose integer type and any valid implicit conversion to it.
11438 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
11439   // Taking into account implicit conversions,
11440   // allow any integer.
11441   if (!E->getType()->isIntegerType()) {
11442     S.Diag(E->getBeginLoc(),
11443            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
11444     return true;
11445   }
11446   // Potentially emit standard warnings for implicit conversions if enabled
11447   // using -Wconversion.
11448   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
11449   return false;
11450 }
11451 
11452 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
11453 // Returns true when emitting a warning about taking the address of a reference.
11454 static bool CheckForReference(Sema &SemaRef, const Expr *E,
11455                               const PartialDiagnostic &PD) {
11456   E = E->IgnoreParenImpCasts();
11457 
11458   const FunctionDecl *FD = nullptr;
11459 
11460   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11461     if (!DRE->getDecl()->getType()->isReferenceType())
11462       return false;
11463   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11464     if (!M->getMemberDecl()->getType()->isReferenceType())
11465       return false;
11466   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
11467     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
11468       return false;
11469     FD = Call->getDirectCallee();
11470   } else {
11471     return false;
11472   }
11473 
11474   SemaRef.Diag(E->getExprLoc(), PD);
11475 
11476   // If possible, point to location of function.
11477   if (FD) {
11478     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
11479   }
11480 
11481   return true;
11482 }
11483 
11484 // Returns true if the SourceLocation is expanded from any macro body.
11485 // Returns false if the SourceLocation is invalid, is from not in a macro
11486 // expansion, or is from expanded from a top-level macro argument.
11487 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
11488   if (Loc.isInvalid())
11489     return false;
11490 
11491   while (Loc.isMacroID()) {
11492     if (SM.isMacroBodyExpansion(Loc))
11493       return true;
11494     Loc = SM.getImmediateMacroCallerLoc(Loc);
11495   }
11496 
11497   return false;
11498 }
11499 
11500 /// Diagnose pointers that are always non-null.
11501 /// \param E the expression containing the pointer
11502 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
11503 /// compared to a null pointer
11504 /// \param IsEqual True when the comparison is equal to a null pointer
11505 /// \param Range Extra SourceRange to highlight in the diagnostic
11506 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
11507                                         Expr::NullPointerConstantKind NullKind,
11508                                         bool IsEqual, SourceRange Range) {
11509   if (!E)
11510     return;
11511 
11512   // Don't warn inside macros.
11513   if (E->getExprLoc().isMacroID()) {
11514     const SourceManager &SM = getSourceManager();
11515     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
11516         IsInAnyMacroBody(SM, Range.getBegin()))
11517       return;
11518   }
11519   E = E->IgnoreImpCasts();
11520 
11521   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
11522 
11523   if (isa<CXXThisExpr>(E)) {
11524     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
11525                                 : diag::warn_this_bool_conversion;
11526     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
11527     return;
11528   }
11529 
11530   bool IsAddressOf = false;
11531 
11532   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11533     if (UO->getOpcode() != UO_AddrOf)
11534       return;
11535     IsAddressOf = true;
11536     E = UO->getSubExpr();
11537   }
11538 
11539   if (IsAddressOf) {
11540     unsigned DiagID = IsCompare
11541                           ? diag::warn_address_of_reference_null_compare
11542                           : diag::warn_address_of_reference_bool_conversion;
11543     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
11544                                          << IsEqual;
11545     if (CheckForReference(*this, E, PD)) {
11546       return;
11547     }
11548   }
11549 
11550   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
11551     bool IsParam = isa<NonNullAttr>(NonnullAttr);
11552     std::string Str;
11553     llvm::raw_string_ostream S(Str);
11554     E->printPretty(S, nullptr, getPrintingPolicy());
11555     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
11556                                 : diag::warn_cast_nonnull_to_bool;
11557     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
11558       << E->getSourceRange() << Range << IsEqual;
11559     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
11560   };
11561 
11562   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
11563   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
11564     if (auto *Callee = Call->getDirectCallee()) {
11565       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
11566         ComplainAboutNonnullParamOrCall(A);
11567         return;
11568       }
11569     }
11570   }
11571 
11572   // Expect to find a single Decl.  Skip anything more complicated.
11573   ValueDecl *D = nullptr;
11574   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
11575     D = R->getDecl();
11576   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
11577     D = M->getMemberDecl();
11578   }
11579 
11580   // Weak Decls can be null.
11581   if (!D || D->isWeak())
11582     return;
11583 
11584   // Check for parameter decl with nonnull attribute
11585   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
11586     if (getCurFunction() &&
11587         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
11588       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
11589         ComplainAboutNonnullParamOrCall(A);
11590         return;
11591       }
11592 
11593       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
11594         auto ParamIter = llvm::find(FD->parameters(), PV);
11595         assert(ParamIter != FD->param_end());
11596         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
11597 
11598         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
11599           if (!NonNull->args_size()) {
11600               ComplainAboutNonnullParamOrCall(NonNull);
11601               return;
11602           }
11603 
11604           for (const ParamIdx &ArgNo : NonNull->args()) {
11605             if (ArgNo.getASTIndex() == ParamNo) {
11606               ComplainAboutNonnullParamOrCall(NonNull);
11607               return;
11608             }
11609           }
11610         }
11611       }
11612     }
11613   }
11614 
11615   QualType T = D->getType();
11616   const bool IsArray = T->isArrayType();
11617   const bool IsFunction = T->isFunctionType();
11618 
11619   // Address of function is used to silence the function warning.
11620   if (IsAddressOf && IsFunction) {
11621     return;
11622   }
11623 
11624   // Found nothing.
11625   if (!IsAddressOf && !IsFunction && !IsArray)
11626     return;
11627 
11628   // Pretty print the expression for the diagnostic.
11629   std::string Str;
11630   llvm::raw_string_ostream S(Str);
11631   E->printPretty(S, nullptr, getPrintingPolicy());
11632 
11633   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
11634                               : diag::warn_impcast_pointer_to_bool;
11635   enum {
11636     AddressOf,
11637     FunctionPointer,
11638     ArrayPointer
11639   } DiagType;
11640   if (IsAddressOf)
11641     DiagType = AddressOf;
11642   else if (IsFunction)
11643     DiagType = FunctionPointer;
11644   else if (IsArray)
11645     DiagType = ArrayPointer;
11646   else
11647     llvm_unreachable("Could not determine diagnostic.");
11648   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
11649                                 << Range << IsEqual;
11650 
11651   if (!IsFunction)
11652     return;
11653 
11654   // Suggest '&' to silence the function warning.
11655   Diag(E->getExprLoc(), diag::note_function_warning_silence)
11656       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
11657 
11658   // Check to see if '()' fixit should be emitted.
11659   QualType ReturnType;
11660   UnresolvedSet<4> NonTemplateOverloads;
11661   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
11662   if (ReturnType.isNull())
11663     return;
11664 
11665   if (IsCompare) {
11666     // There are two cases here.  If there is null constant, the only suggest
11667     // for a pointer return type.  If the null is 0, then suggest if the return
11668     // type is a pointer or an integer type.
11669     if (!ReturnType->isPointerType()) {
11670       if (NullKind == Expr::NPCK_ZeroExpression ||
11671           NullKind == Expr::NPCK_ZeroLiteral) {
11672         if (!ReturnType->isIntegerType())
11673           return;
11674       } else {
11675         return;
11676       }
11677     }
11678   } else { // !IsCompare
11679     // For function to bool, only suggest if the function pointer has bool
11680     // return type.
11681     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
11682       return;
11683   }
11684   Diag(E->getExprLoc(), diag::note_function_to_function_call)
11685       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
11686 }
11687 
11688 /// Diagnoses "dangerous" implicit conversions within the given
11689 /// expression (which is a full expression).  Implements -Wconversion
11690 /// and -Wsign-compare.
11691 ///
11692 /// \param CC the "context" location of the implicit conversion, i.e.
11693 ///   the most location of the syntactic entity requiring the implicit
11694 ///   conversion
11695 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
11696   // Don't diagnose in unevaluated contexts.
11697   if (isUnevaluatedContext())
11698     return;
11699 
11700   // Don't diagnose for value- or type-dependent expressions.
11701   if (E->isTypeDependent() || E->isValueDependent())
11702     return;
11703 
11704   // Check for array bounds violations in cases where the check isn't triggered
11705   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
11706   // ArraySubscriptExpr is on the RHS of a variable initialization.
11707   CheckArrayAccess(E);
11708 
11709   // This is not the right CC for (e.g.) a variable initialization.
11710   AnalyzeImplicitConversions(*this, E, CC);
11711 }
11712 
11713 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
11714 /// Input argument E is a logical expression.
11715 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
11716   ::CheckBoolLikeConversion(*this, E, CC);
11717 }
11718 
11719 /// Diagnose when expression is an integer constant expression and its evaluation
11720 /// results in integer overflow
11721 void Sema::CheckForIntOverflow (Expr *E) {
11722   // Use a work list to deal with nested struct initializers.
11723   SmallVector<Expr *, 2> Exprs(1, E);
11724 
11725   do {
11726     Expr *OriginalE = Exprs.pop_back_val();
11727     Expr *E = OriginalE->IgnoreParenCasts();
11728 
11729     if (isa<BinaryOperator>(E)) {
11730       E->EvaluateForOverflow(Context);
11731       continue;
11732     }
11733 
11734     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
11735       Exprs.append(InitList->inits().begin(), InitList->inits().end());
11736     else if (isa<ObjCBoxedExpr>(OriginalE))
11737       E->EvaluateForOverflow(Context);
11738     else if (auto Call = dyn_cast<CallExpr>(E))
11739       Exprs.append(Call->arg_begin(), Call->arg_end());
11740     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
11741       Exprs.append(Message->arg_begin(), Message->arg_end());
11742   } while (!Exprs.empty());
11743 }
11744 
11745 namespace {
11746 
11747 /// Visitor for expressions which looks for unsequenced operations on the
11748 /// same object.
11749 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
11750   using Base = EvaluatedExprVisitor<SequenceChecker>;
11751 
11752   /// A tree of sequenced regions within an expression. Two regions are
11753   /// unsequenced if one is an ancestor or a descendent of the other. When we
11754   /// finish processing an expression with sequencing, such as a comma
11755   /// expression, we fold its tree nodes into its parent, since they are
11756   /// unsequenced with respect to nodes we will visit later.
11757   class SequenceTree {
11758     struct Value {
11759       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
11760       unsigned Parent : 31;
11761       unsigned Merged : 1;
11762     };
11763     SmallVector<Value, 8> Values;
11764 
11765   public:
11766     /// A region within an expression which may be sequenced with respect
11767     /// to some other region.
11768     class Seq {
11769       friend class SequenceTree;
11770 
11771       unsigned Index;
11772 
11773       explicit Seq(unsigned N) : Index(N) {}
11774 
11775     public:
11776       Seq() : Index(0) {}
11777     };
11778 
11779     SequenceTree() { Values.push_back(Value(0)); }
11780     Seq root() const { return Seq(0); }
11781 
11782     /// Create a new sequence of operations, which is an unsequenced
11783     /// subset of \p Parent. This sequence of operations is sequenced with
11784     /// respect to other children of \p Parent.
11785     Seq allocate(Seq Parent) {
11786       Values.push_back(Value(Parent.Index));
11787       return Seq(Values.size() - 1);
11788     }
11789 
11790     /// Merge a sequence of operations into its parent.
11791     void merge(Seq S) {
11792       Values[S.Index].Merged = true;
11793     }
11794 
11795     /// Determine whether two operations are unsequenced. This operation
11796     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
11797     /// should have been merged into its parent as appropriate.
11798     bool isUnsequenced(Seq Cur, Seq Old) {
11799       unsigned C = representative(Cur.Index);
11800       unsigned Target = representative(Old.Index);
11801       while (C >= Target) {
11802         if (C == Target)
11803           return true;
11804         C = Values[C].Parent;
11805       }
11806       return false;
11807     }
11808 
11809   private:
11810     /// Pick a representative for a sequence.
11811     unsigned representative(unsigned K) {
11812       if (Values[K].Merged)
11813         // Perform path compression as we go.
11814         return Values[K].Parent = representative(Values[K].Parent);
11815       return K;
11816     }
11817   };
11818 
11819   /// An object for which we can track unsequenced uses.
11820   using Object = NamedDecl *;
11821 
11822   /// Different flavors of object usage which we track. We only track the
11823   /// least-sequenced usage of each kind.
11824   enum UsageKind {
11825     /// A read of an object. Multiple unsequenced reads are OK.
11826     UK_Use,
11827 
11828     /// A modification of an object which is sequenced before the value
11829     /// computation of the expression, such as ++n in C++.
11830     UK_ModAsValue,
11831 
11832     /// A modification of an object which is not sequenced before the value
11833     /// computation of the expression, such as n++.
11834     UK_ModAsSideEffect,
11835 
11836     UK_Count = UK_ModAsSideEffect + 1
11837   };
11838 
11839   struct Usage {
11840     Expr *Use;
11841     SequenceTree::Seq Seq;
11842 
11843     Usage() : Use(nullptr), Seq() {}
11844   };
11845 
11846   struct UsageInfo {
11847     Usage Uses[UK_Count];
11848 
11849     /// Have we issued a diagnostic for this variable already?
11850     bool Diagnosed;
11851 
11852     UsageInfo() : Uses(), Diagnosed(false) {}
11853   };
11854   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
11855 
11856   Sema &SemaRef;
11857 
11858   /// Sequenced regions within the expression.
11859   SequenceTree Tree;
11860 
11861   /// Declaration modifications and references which we have seen.
11862   UsageInfoMap UsageMap;
11863 
11864   /// The region we are currently within.
11865   SequenceTree::Seq Region;
11866 
11867   /// Filled in with declarations which were modified as a side-effect
11868   /// (that is, post-increment operations).
11869   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
11870 
11871   /// Expressions to check later. We defer checking these to reduce
11872   /// stack usage.
11873   SmallVectorImpl<Expr *> &WorkList;
11874 
11875   /// RAII object wrapping the visitation of a sequenced subexpression of an
11876   /// expression. At the end of this process, the side-effects of the evaluation
11877   /// become sequenced with respect to the value computation of the result, so
11878   /// we downgrade any UK_ModAsSideEffect within the evaluation to
11879   /// UK_ModAsValue.
11880   struct SequencedSubexpression {
11881     SequencedSubexpression(SequenceChecker &Self)
11882       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
11883       Self.ModAsSideEffect = &ModAsSideEffect;
11884     }
11885 
11886     ~SequencedSubexpression() {
11887       for (auto &M : llvm::reverse(ModAsSideEffect)) {
11888         UsageInfo &U = Self.UsageMap[M.first];
11889         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
11890         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
11891         SideEffectUsage = M.second;
11892       }
11893       Self.ModAsSideEffect = OldModAsSideEffect;
11894     }
11895 
11896     SequenceChecker &Self;
11897     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
11898     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
11899   };
11900 
11901   /// RAII object wrapping the visitation of a subexpression which we might
11902   /// choose to evaluate as a constant. If any subexpression is evaluated and
11903   /// found to be non-constant, this allows us to suppress the evaluation of
11904   /// the outer expression.
11905   class EvaluationTracker {
11906   public:
11907     EvaluationTracker(SequenceChecker &Self)
11908         : Self(Self), Prev(Self.EvalTracker) {
11909       Self.EvalTracker = this;
11910     }
11911 
11912     ~EvaluationTracker() {
11913       Self.EvalTracker = Prev;
11914       if (Prev)
11915         Prev->EvalOK &= EvalOK;
11916     }
11917 
11918     bool evaluate(const Expr *E, bool &Result) {
11919       if (!EvalOK || E->isValueDependent())
11920         return false;
11921       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
11922       return EvalOK;
11923     }
11924 
11925   private:
11926     SequenceChecker &Self;
11927     EvaluationTracker *Prev;
11928     bool EvalOK = true;
11929   } *EvalTracker = nullptr;
11930 
11931   /// Find the object which is produced by the specified expression,
11932   /// if any.
11933   Object getObject(Expr *E, bool Mod) const {
11934     E = E->IgnoreParenCasts();
11935     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
11936       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
11937         return getObject(UO->getSubExpr(), Mod);
11938     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11939       if (BO->getOpcode() == BO_Comma)
11940         return getObject(BO->getRHS(), Mod);
11941       if (Mod && BO->isAssignmentOp())
11942         return getObject(BO->getLHS(), Mod);
11943     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11944       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
11945       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
11946         return ME->getMemberDecl();
11947     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11948       // FIXME: If this is a reference, map through to its value.
11949       return DRE->getDecl();
11950     return nullptr;
11951   }
11952 
11953   /// Note that an object was modified or used by an expression.
11954   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
11955     Usage &U = UI.Uses[UK];
11956     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
11957       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
11958         ModAsSideEffect->push_back(std::make_pair(O, U));
11959       U.Use = Ref;
11960       U.Seq = Region;
11961     }
11962   }
11963 
11964   /// Check whether a modification or use conflicts with a prior usage.
11965   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
11966                   bool IsModMod) {
11967     if (UI.Diagnosed)
11968       return;
11969 
11970     const Usage &U = UI.Uses[OtherKind];
11971     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
11972       return;
11973 
11974     Expr *Mod = U.Use;
11975     Expr *ModOrUse = Ref;
11976     if (OtherKind == UK_Use)
11977       std::swap(Mod, ModOrUse);
11978 
11979     SemaRef.Diag(Mod->getExprLoc(),
11980                  IsModMod ? diag::warn_unsequenced_mod_mod
11981                           : diag::warn_unsequenced_mod_use)
11982       << O << SourceRange(ModOrUse->getExprLoc());
11983     UI.Diagnosed = true;
11984   }
11985 
11986   void notePreUse(Object O, Expr *Use) {
11987     UsageInfo &U = UsageMap[O];
11988     // Uses conflict with other modifications.
11989     checkUsage(O, U, Use, UK_ModAsValue, false);
11990   }
11991 
11992   void notePostUse(Object O, Expr *Use) {
11993     UsageInfo &U = UsageMap[O];
11994     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
11995     addUsage(U, O, Use, UK_Use);
11996   }
11997 
11998   void notePreMod(Object O, Expr *Mod) {
11999     UsageInfo &U = UsageMap[O];
12000     // Modifications conflict with other modifications and with uses.
12001     checkUsage(O, U, Mod, UK_ModAsValue, true);
12002     checkUsage(O, U, Mod, UK_Use, false);
12003   }
12004 
12005   void notePostMod(Object O, Expr *Use, UsageKind UK) {
12006     UsageInfo &U = UsageMap[O];
12007     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
12008     addUsage(U, O, Use, UK);
12009   }
12010 
12011 public:
12012   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
12013       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
12014     Visit(E);
12015   }
12016 
12017   void VisitStmt(Stmt *S) {
12018     // Skip all statements which aren't expressions for now.
12019   }
12020 
12021   void VisitExpr(Expr *E) {
12022     // By default, just recurse to evaluated subexpressions.
12023     Base::VisitStmt(E);
12024   }
12025 
12026   void VisitCastExpr(CastExpr *E) {
12027     Object O = Object();
12028     if (E->getCastKind() == CK_LValueToRValue)
12029       O = getObject(E->getSubExpr(), false);
12030 
12031     if (O)
12032       notePreUse(O, E);
12033     VisitExpr(E);
12034     if (O)
12035       notePostUse(O, E);
12036   }
12037 
12038   void VisitSequencedExpressions(Expr *SequencedBefore, Expr *SequencedAfter) {
12039     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
12040     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
12041     SequenceTree::Seq OldRegion = Region;
12042 
12043     {
12044       SequencedSubexpression SeqBefore(*this);
12045       Region = BeforeRegion;
12046       Visit(SequencedBefore);
12047     }
12048 
12049     Region = AfterRegion;
12050     Visit(SequencedAfter);
12051 
12052     Region = OldRegion;
12053 
12054     Tree.merge(BeforeRegion);
12055     Tree.merge(AfterRegion);
12056   }
12057 
12058   void VisitArraySubscriptExpr(ArraySubscriptExpr *ASE) {
12059     // C++17 [expr.sub]p1:
12060     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
12061     //   expression E1 is sequenced before the expression E2.
12062     if (SemaRef.getLangOpts().CPlusPlus17)
12063       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
12064     else
12065       Base::VisitStmt(ASE);
12066   }
12067 
12068   void VisitBinComma(BinaryOperator *BO) {
12069     // C++11 [expr.comma]p1:
12070     //   Every value computation and side effect associated with the left
12071     //   expression is sequenced before every value computation and side
12072     //   effect associated with the right expression.
12073     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
12074   }
12075 
12076   void VisitBinAssign(BinaryOperator *BO) {
12077     // The modification is sequenced after the value computation of the LHS
12078     // and RHS, so check it before inspecting the operands and update the
12079     // map afterwards.
12080     Object O = getObject(BO->getLHS(), true);
12081     if (!O)
12082       return VisitExpr(BO);
12083 
12084     notePreMod(O, BO);
12085 
12086     // C++11 [expr.ass]p7:
12087     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
12088     //   only once.
12089     //
12090     // Therefore, for a compound assignment operator, O is considered used
12091     // everywhere except within the evaluation of E1 itself.
12092     if (isa<CompoundAssignOperator>(BO))
12093       notePreUse(O, BO);
12094 
12095     Visit(BO->getLHS());
12096 
12097     if (isa<CompoundAssignOperator>(BO))
12098       notePostUse(O, BO);
12099 
12100     Visit(BO->getRHS());
12101 
12102     // C++11 [expr.ass]p1:
12103     //   the assignment is sequenced [...] before the value computation of the
12104     //   assignment expression.
12105     // C11 6.5.16/3 has no such rule.
12106     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12107                                                        : UK_ModAsSideEffect);
12108   }
12109 
12110   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
12111     VisitBinAssign(CAO);
12112   }
12113 
12114   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12115   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
12116   void VisitUnaryPreIncDec(UnaryOperator *UO) {
12117     Object O = getObject(UO->getSubExpr(), true);
12118     if (!O)
12119       return VisitExpr(UO);
12120 
12121     notePreMod(O, UO);
12122     Visit(UO->getSubExpr());
12123     // C++11 [expr.pre.incr]p1:
12124     //   the expression ++x is equivalent to x+=1
12125     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
12126                                                        : UK_ModAsSideEffect);
12127   }
12128 
12129   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12130   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
12131   void VisitUnaryPostIncDec(UnaryOperator *UO) {
12132     Object O = getObject(UO->getSubExpr(), true);
12133     if (!O)
12134       return VisitExpr(UO);
12135 
12136     notePreMod(O, UO);
12137     Visit(UO->getSubExpr());
12138     notePostMod(O, UO, UK_ModAsSideEffect);
12139   }
12140 
12141   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
12142   void VisitBinLOr(BinaryOperator *BO) {
12143     // The side-effects of the LHS of an '&&' are sequenced before the
12144     // value computation of the RHS, and hence before the value computation
12145     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
12146     // as if they were unconditionally sequenced.
12147     EvaluationTracker Eval(*this);
12148     {
12149       SequencedSubexpression Sequenced(*this);
12150       Visit(BO->getLHS());
12151     }
12152 
12153     bool Result;
12154     if (Eval.evaluate(BO->getLHS(), Result)) {
12155       if (!Result)
12156         Visit(BO->getRHS());
12157     } else {
12158       // Check for unsequenced operations in the RHS, treating it as an
12159       // entirely separate evaluation.
12160       //
12161       // FIXME: If there are operations in the RHS which are unsequenced
12162       // with respect to operations outside the RHS, and those operations
12163       // are unconditionally evaluated, diagnose them.
12164       WorkList.push_back(BO->getRHS());
12165     }
12166   }
12167   void VisitBinLAnd(BinaryOperator *BO) {
12168     EvaluationTracker Eval(*this);
12169     {
12170       SequencedSubexpression Sequenced(*this);
12171       Visit(BO->getLHS());
12172     }
12173 
12174     bool Result;
12175     if (Eval.evaluate(BO->getLHS(), Result)) {
12176       if (Result)
12177         Visit(BO->getRHS());
12178     } else {
12179       WorkList.push_back(BO->getRHS());
12180     }
12181   }
12182 
12183   // Only visit the condition, unless we can be sure which subexpression will
12184   // be chosen.
12185   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
12186     EvaluationTracker Eval(*this);
12187     {
12188       SequencedSubexpression Sequenced(*this);
12189       Visit(CO->getCond());
12190     }
12191 
12192     bool Result;
12193     if (Eval.evaluate(CO->getCond(), Result))
12194       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
12195     else {
12196       WorkList.push_back(CO->getTrueExpr());
12197       WorkList.push_back(CO->getFalseExpr());
12198     }
12199   }
12200 
12201   void VisitCallExpr(CallExpr *CE) {
12202     // C++11 [intro.execution]p15:
12203     //   When calling a function [...], every value computation and side effect
12204     //   associated with any argument expression, or with the postfix expression
12205     //   designating the called function, is sequenced before execution of every
12206     //   expression or statement in the body of the function [and thus before
12207     //   the value computation of its result].
12208     SequencedSubexpression Sequenced(*this);
12209     Base::VisitCallExpr(CE);
12210 
12211     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
12212   }
12213 
12214   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
12215     // This is a call, so all subexpressions are sequenced before the result.
12216     SequencedSubexpression Sequenced(*this);
12217 
12218     if (!CCE->isListInitialization())
12219       return VisitExpr(CCE);
12220 
12221     // In C++11, list initializations are sequenced.
12222     SmallVector<SequenceTree::Seq, 32> Elts;
12223     SequenceTree::Seq Parent = Region;
12224     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
12225                                         E = CCE->arg_end();
12226          I != E; ++I) {
12227       Region = Tree.allocate(Parent);
12228       Elts.push_back(Region);
12229       Visit(*I);
12230     }
12231 
12232     // Forget that the initializers are sequenced.
12233     Region = Parent;
12234     for (unsigned I = 0; I < Elts.size(); ++I)
12235       Tree.merge(Elts[I]);
12236   }
12237 
12238   void VisitInitListExpr(InitListExpr *ILE) {
12239     if (!SemaRef.getLangOpts().CPlusPlus11)
12240       return VisitExpr(ILE);
12241 
12242     // In C++11, list initializations are sequenced.
12243     SmallVector<SequenceTree::Seq, 32> Elts;
12244     SequenceTree::Seq Parent = Region;
12245     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
12246       Expr *E = ILE->getInit(I);
12247       if (!E) continue;
12248       Region = Tree.allocate(Parent);
12249       Elts.push_back(Region);
12250       Visit(E);
12251     }
12252 
12253     // Forget that the initializers are sequenced.
12254     Region = Parent;
12255     for (unsigned I = 0; I < Elts.size(); ++I)
12256       Tree.merge(Elts[I]);
12257   }
12258 };
12259 
12260 } // namespace
12261 
12262 void Sema::CheckUnsequencedOperations(Expr *E) {
12263   SmallVector<Expr *, 8> WorkList;
12264   WorkList.push_back(E);
12265   while (!WorkList.empty()) {
12266     Expr *Item = WorkList.pop_back_val();
12267     SequenceChecker(*this, Item, WorkList);
12268   }
12269 }
12270 
12271 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
12272                               bool IsConstexpr) {
12273   CheckImplicitConversions(E, CheckLoc);
12274   if (!E->isInstantiationDependent())
12275     CheckUnsequencedOperations(E);
12276   if (!IsConstexpr && !E->isValueDependent())
12277     CheckForIntOverflow(E);
12278   DiagnoseMisalignedMembers();
12279 }
12280 
12281 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
12282                                        FieldDecl *BitField,
12283                                        Expr *Init) {
12284   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
12285 }
12286 
12287 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
12288                                          SourceLocation Loc) {
12289   if (!PType->isVariablyModifiedType())
12290     return;
12291   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
12292     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
12293     return;
12294   }
12295   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
12296     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
12297     return;
12298   }
12299   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
12300     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
12301     return;
12302   }
12303 
12304   const ArrayType *AT = S.Context.getAsArrayType(PType);
12305   if (!AT)
12306     return;
12307 
12308   if (AT->getSizeModifier() != ArrayType::Star) {
12309     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
12310     return;
12311   }
12312 
12313   S.Diag(Loc, diag::err_array_star_in_function_definition);
12314 }
12315 
12316 /// CheckParmsForFunctionDef - Check that the parameters of the given
12317 /// function are appropriate for the definition of a function. This
12318 /// takes care of any checks that cannot be performed on the
12319 /// declaration itself, e.g., that the types of each of the function
12320 /// parameters are complete.
12321 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
12322                                     bool CheckParameterNames) {
12323   bool HasInvalidParm = false;
12324   for (ParmVarDecl *Param : Parameters) {
12325     // C99 6.7.5.3p4: the parameters in a parameter type list in a
12326     // function declarator that is part of a function definition of
12327     // that function shall not have incomplete type.
12328     //
12329     // This is also C++ [dcl.fct]p6.
12330     if (!Param->isInvalidDecl() &&
12331         RequireCompleteType(Param->getLocation(), Param->getType(),
12332                             diag::err_typecheck_decl_incomplete_type)) {
12333       Param->setInvalidDecl();
12334       HasInvalidParm = true;
12335     }
12336 
12337     // C99 6.9.1p5: If the declarator includes a parameter type list, the
12338     // declaration of each parameter shall include an identifier.
12339     if (CheckParameterNames &&
12340         Param->getIdentifier() == nullptr &&
12341         !Param->isImplicit() &&
12342         !getLangOpts().CPlusPlus)
12343       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12344 
12345     // C99 6.7.5.3p12:
12346     //   If the function declarator is not part of a definition of that
12347     //   function, parameters may have incomplete type and may use the [*]
12348     //   notation in their sequences of declarator specifiers to specify
12349     //   variable length array types.
12350     QualType PType = Param->getOriginalType();
12351     // FIXME: This diagnostic should point the '[*]' if source-location
12352     // information is added for it.
12353     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
12354 
12355     // If the parameter is a c++ class type and it has to be destructed in the
12356     // callee function, declare the destructor so that it can be called by the
12357     // callee function. Do not perform any direct access check on the dtor here.
12358     if (!Param->isInvalidDecl()) {
12359       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
12360         if (!ClassDecl->isInvalidDecl() &&
12361             !ClassDecl->hasIrrelevantDestructor() &&
12362             !ClassDecl->isDependentContext() &&
12363             ClassDecl->isParamDestroyedInCallee()) {
12364           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12365           MarkFunctionReferenced(Param->getLocation(), Destructor);
12366           DiagnoseUseOfDecl(Destructor, Param->getLocation());
12367         }
12368       }
12369     }
12370 
12371     // Parameters with the pass_object_size attribute only need to be marked
12372     // constant at function definitions. Because we lack information about
12373     // whether we're on a declaration or definition when we're instantiating the
12374     // attribute, we need to check for constness here.
12375     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
12376       if (!Param->getType().isConstQualified())
12377         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
12378             << Attr->getSpelling() << 1;
12379 
12380     // Check for parameter names shadowing fields from the class.
12381     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
12382       // The owning context for the parameter should be the function, but we
12383       // want to see if this function's declaration context is a record.
12384       DeclContext *DC = Param->getDeclContext();
12385       if (DC && DC->isFunctionOrMethod()) {
12386         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
12387           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
12388                                      RD, /*DeclIsField*/ false);
12389       }
12390     }
12391   }
12392 
12393   return HasInvalidParm;
12394 }
12395 
12396 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
12397 /// or MemberExpr.
12398 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
12399                               ASTContext &Context) {
12400   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
12401     return Context.getDeclAlign(DRE->getDecl());
12402 
12403   if (const auto *ME = dyn_cast<MemberExpr>(E))
12404     return Context.getDeclAlign(ME->getMemberDecl());
12405 
12406   return TypeAlign;
12407 }
12408 
12409 /// CheckCastAlign - Implements -Wcast-align, which warns when a
12410 /// pointer cast increases the alignment requirements.
12411 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
12412   // This is actually a lot of work to potentially be doing on every
12413   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
12414   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
12415     return;
12416 
12417   // Ignore dependent types.
12418   if (T->isDependentType() || Op->getType()->isDependentType())
12419     return;
12420 
12421   // Require that the destination be a pointer type.
12422   const PointerType *DestPtr = T->getAs<PointerType>();
12423   if (!DestPtr) return;
12424 
12425   // If the destination has alignment 1, we're done.
12426   QualType DestPointee = DestPtr->getPointeeType();
12427   if (DestPointee->isIncompleteType()) return;
12428   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
12429   if (DestAlign.isOne()) return;
12430 
12431   // Require that the source be a pointer type.
12432   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
12433   if (!SrcPtr) return;
12434   QualType SrcPointee = SrcPtr->getPointeeType();
12435 
12436   // Whitelist casts from cv void*.  We already implicitly
12437   // whitelisted casts to cv void*, since they have alignment 1.
12438   // Also whitelist casts involving incomplete types, which implicitly
12439   // includes 'void'.
12440   if (SrcPointee->isIncompleteType()) return;
12441 
12442   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
12443 
12444   if (auto *CE = dyn_cast<CastExpr>(Op)) {
12445     if (CE->getCastKind() == CK_ArrayToPointerDecay)
12446       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
12447   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
12448     if (UO->getOpcode() == UO_AddrOf)
12449       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
12450   }
12451 
12452   if (SrcAlign >= DestAlign) return;
12453 
12454   Diag(TRange.getBegin(), diag::warn_cast_align)
12455     << Op->getType() << T
12456     << static_cast<unsigned>(SrcAlign.getQuantity())
12457     << static_cast<unsigned>(DestAlign.getQuantity())
12458     << TRange << Op->getSourceRange();
12459 }
12460 
12461 /// Check whether this array fits the idiom of a size-one tail padded
12462 /// array member of a struct.
12463 ///
12464 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
12465 /// commonly used to emulate flexible arrays in C89 code.
12466 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
12467                                     const NamedDecl *ND) {
12468   if (Size != 1 || !ND) return false;
12469 
12470   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
12471   if (!FD) return false;
12472 
12473   // Don't consider sizes resulting from macro expansions or template argument
12474   // substitution to form C89 tail-padded arrays.
12475 
12476   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
12477   while (TInfo) {
12478     TypeLoc TL = TInfo->getTypeLoc();
12479     // Look through typedefs.
12480     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
12481       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
12482       TInfo = TDL->getTypeSourceInfo();
12483       continue;
12484     }
12485     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
12486       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
12487       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
12488         return false;
12489     }
12490     break;
12491   }
12492 
12493   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
12494   if (!RD) return false;
12495   if (RD->isUnion()) return false;
12496   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12497     if (!CRD->isStandardLayout()) return false;
12498   }
12499 
12500   // See if this is the last field decl in the record.
12501   const Decl *D = FD;
12502   while ((D = D->getNextDeclInContext()))
12503     if (isa<FieldDecl>(D))
12504       return false;
12505   return true;
12506 }
12507 
12508 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12509                             const ArraySubscriptExpr *ASE,
12510                             bool AllowOnePastEnd, bool IndexNegated) {
12511   IndexExpr = IndexExpr->IgnoreParenImpCasts();
12512   if (IndexExpr->isValueDependent())
12513     return;
12514 
12515   const Type *EffectiveType =
12516       BaseExpr->getType()->getPointeeOrArrayElementType();
12517   BaseExpr = BaseExpr->IgnoreParenCasts();
12518   const ConstantArrayType *ArrayTy =
12519       Context.getAsConstantArrayType(BaseExpr->getType());
12520 
12521   if (!ArrayTy)
12522     return;
12523 
12524   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
12525 
12526   Expr::EvalResult Result;
12527   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
12528     return;
12529 
12530   llvm::APSInt index = Result.Val.getInt();
12531   if (IndexNegated)
12532     index = -index;
12533 
12534   const NamedDecl *ND = nullptr;
12535   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12536     ND = DRE->getDecl();
12537   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12538     ND = ME->getMemberDecl();
12539 
12540   if (index.isUnsigned() || !index.isNegative()) {
12541     // It is possible that the type of the base expression after
12542     // IgnoreParenCasts is incomplete, even though the type of the base
12543     // expression before IgnoreParenCasts is complete (see PR39746 for an
12544     // example). In this case we have no information about whether the array
12545     // access exceeds the array bounds. However we can still diagnose an array
12546     // access which precedes the array bounds.
12547     if (BaseType->isIncompleteType())
12548       return;
12549 
12550     llvm::APInt size = ArrayTy->getSize();
12551     if (!size.isStrictlyPositive())
12552       return;
12553 
12554     if (BaseType != EffectiveType) {
12555       // Make sure we're comparing apples to apples when comparing index to size
12556       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
12557       uint64_t array_typesize = Context.getTypeSize(BaseType);
12558       // Handle ptrarith_typesize being zero, such as when casting to void*
12559       if (!ptrarith_typesize) ptrarith_typesize = 1;
12560       if (ptrarith_typesize != array_typesize) {
12561         // There's a cast to a different size type involved
12562         uint64_t ratio = array_typesize / ptrarith_typesize;
12563         // TODO: Be smarter about handling cases where array_typesize is not a
12564         // multiple of ptrarith_typesize
12565         if (ptrarith_typesize * ratio == array_typesize)
12566           size *= llvm::APInt(size.getBitWidth(), ratio);
12567       }
12568     }
12569 
12570     if (size.getBitWidth() > index.getBitWidth())
12571       index = index.zext(size.getBitWidth());
12572     else if (size.getBitWidth() < index.getBitWidth())
12573       size = size.zext(index.getBitWidth());
12574 
12575     // For array subscripting the index must be less than size, but for pointer
12576     // arithmetic also allow the index (offset) to be equal to size since
12577     // computing the next address after the end of the array is legal and
12578     // commonly done e.g. in C++ iterators and range-based for loops.
12579     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
12580       return;
12581 
12582     // Also don't warn for arrays of size 1 which are members of some
12583     // structure. These are often used to approximate flexible arrays in C89
12584     // code.
12585     if (IsTailPaddedMemberArray(*this, size, ND))
12586       return;
12587 
12588     // Suppress the warning if the subscript expression (as identified by the
12589     // ']' location) and the index expression are both from macro expansions
12590     // within a system header.
12591     if (ASE) {
12592       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
12593           ASE->getRBracketLoc());
12594       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
12595         SourceLocation IndexLoc =
12596             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
12597         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
12598           return;
12599       }
12600     }
12601 
12602     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
12603     if (ASE)
12604       DiagID = diag::warn_array_index_exceeds_bounds;
12605 
12606     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12607                         PDiag(DiagID) << index.toString(10, true)
12608                                       << size.toString(10, true)
12609                                       << (unsigned)size.getLimitedValue(~0U)
12610                                       << IndexExpr->getSourceRange());
12611   } else {
12612     unsigned DiagID = diag::warn_array_index_precedes_bounds;
12613     if (!ASE) {
12614       DiagID = diag::warn_ptr_arith_precedes_bounds;
12615       if (index.isNegative()) index = -index;
12616     }
12617 
12618     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
12619                         PDiag(DiagID) << index.toString(10, true)
12620                                       << IndexExpr->getSourceRange());
12621   }
12622 
12623   if (!ND) {
12624     // Try harder to find a NamedDecl to point at in the note.
12625     while (const ArraySubscriptExpr *ASE =
12626            dyn_cast<ArraySubscriptExpr>(BaseExpr))
12627       BaseExpr = ASE->getBase()->IgnoreParenCasts();
12628     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
12629       ND = DRE->getDecl();
12630     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
12631       ND = ME->getMemberDecl();
12632   }
12633 
12634   if (ND)
12635     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
12636                         PDiag(diag::note_array_index_out_of_bounds)
12637                             << ND->getDeclName());
12638 }
12639 
12640 void Sema::CheckArrayAccess(const Expr *expr) {
12641   int AllowOnePastEnd = 0;
12642   while (expr) {
12643     expr = expr->IgnoreParenImpCasts();
12644     switch (expr->getStmtClass()) {
12645       case Stmt::ArraySubscriptExprClass: {
12646         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
12647         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
12648                          AllowOnePastEnd > 0);
12649         expr = ASE->getBase();
12650         break;
12651       }
12652       case Stmt::MemberExprClass: {
12653         expr = cast<MemberExpr>(expr)->getBase();
12654         break;
12655       }
12656       case Stmt::OMPArraySectionExprClass: {
12657         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
12658         if (ASE->getLowerBound())
12659           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
12660                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
12661         return;
12662       }
12663       case Stmt::UnaryOperatorClass: {
12664         // Only unwrap the * and & unary operators
12665         const UnaryOperator *UO = cast<UnaryOperator>(expr);
12666         expr = UO->getSubExpr();
12667         switch (UO->getOpcode()) {
12668           case UO_AddrOf:
12669             AllowOnePastEnd++;
12670             break;
12671           case UO_Deref:
12672             AllowOnePastEnd--;
12673             break;
12674           default:
12675             return;
12676         }
12677         break;
12678       }
12679       case Stmt::ConditionalOperatorClass: {
12680         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
12681         if (const Expr *lhs = cond->getLHS())
12682           CheckArrayAccess(lhs);
12683         if (const Expr *rhs = cond->getRHS())
12684           CheckArrayAccess(rhs);
12685         return;
12686       }
12687       case Stmt::CXXOperatorCallExprClass: {
12688         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
12689         for (const auto *Arg : OCE->arguments())
12690           CheckArrayAccess(Arg);
12691         return;
12692       }
12693       default:
12694         return;
12695     }
12696   }
12697 }
12698 
12699 //===--- CHECK: Objective-C retain cycles ----------------------------------//
12700 
12701 namespace {
12702 
12703 struct RetainCycleOwner {
12704   VarDecl *Variable = nullptr;
12705   SourceRange Range;
12706   SourceLocation Loc;
12707   bool Indirect = false;
12708 
12709   RetainCycleOwner() = default;
12710 
12711   void setLocsFrom(Expr *e) {
12712     Loc = e->getExprLoc();
12713     Range = e->getSourceRange();
12714   }
12715 };
12716 
12717 } // namespace
12718 
12719 /// Consider whether capturing the given variable can possibly lead to
12720 /// a retain cycle.
12721 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
12722   // In ARC, it's captured strongly iff the variable has __strong
12723   // lifetime.  In MRR, it's captured strongly if the variable is
12724   // __block and has an appropriate type.
12725   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12726     return false;
12727 
12728   owner.Variable = var;
12729   if (ref)
12730     owner.setLocsFrom(ref);
12731   return true;
12732 }
12733 
12734 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
12735   while (true) {
12736     e = e->IgnoreParens();
12737     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
12738       switch (cast->getCastKind()) {
12739       case CK_BitCast:
12740       case CK_LValueBitCast:
12741       case CK_LValueToRValue:
12742       case CK_ARCReclaimReturnedObject:
12743         e = cast->getSubExpr();
12744         continue;
12745 
12746       default:
12747         return false;
12748       }
12749     }
12750 
12751     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
12752       ObjCIvarDecl *ivar = ref->getDecl();
12753       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
12754         return false;
12755 
12756       // Try to find a retain cycle in the base.
12757       if (!findRetainCycleOwner(S, ref->getBase(), owner))
12758         return false;
12759 
12760       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
12761       owner.Indirect = true;
12762       return true;
12763     }
12764 
12765     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
12766       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
12767       if (!var) return false;
12768       return considerVariable(var, ref, owner);
12769     }
12770 
12771     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
12772       if (member->isArrow()) return false;
12773 
12774       // Don't count this as an indirect ownership.
12775       e = member->getBase();
12776       continue;
12777     }
12778 
12779     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
12780       // Only pay attention to pseudo-objects on property references.
12781       ObjCPropertyRefExpr *pre
12782         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
12783                                               ->IgnoreParens());
12784       if (!pre) return false;
12785       if (pre->isImplicitProperty()) return false;
12786       ObjCPropertyDecl *property = pre->getExplicitProperty();
12787       if (!property->isRetaining() &&
12788           !(property->getPropertyIvarDecl() &&
12789             property->getPropertyIvarDecl()->getType()
12790               .getObjCLifetime() == Qualifiers::OCL_Strong))
12791           return false;
12792 
12793       owner.Indirect = true;
12794       if (pre->isSuperReceiver()) {
12795         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
12796         if (!owner.Variable)
12797           return false;
12798         owner.Loc = pre->getLocation();
12799         owner.Range = pre->getSourceRange();
12800         return true;
12801       }
12802       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
12803                               ->getSourceExpr());
12804       continue;
12805     }
12806 
12807     // Array ivars?
12808 
12809     return false;
12810   }
12811 }
12812 
12813 namespace {
12814 
12815   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
12816     ASTContext &Context;
12817     VarDecl *Variable;
12818     Expr *Capturer = nullptr;
12819     bool VarWillBeReased = false;
12820 
12821     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
12822         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
12823           Context(Context), Variable(variable) {}
12824 
12825     void VisitDeclRefExpr(DeclRefExpr *ref) {
12826       if (ref->getDecl() == Variable && !Capturer)
12827         Capturer = ref;
12828     }
12829 
12830     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
12831       if (Capturer) return;
12832       Visit(ref->getBase());
12833       if (Capturer && ref->isFreeIvar())
12834         Capturer = ref;
12835     }
12836 
12837     void VisitBlockExpr(BlockExpr *block) {
12838       // Look inside nested blocks
12839       if (block->getBlockDecl()->capturesVariable(Variable))
12840         Visit(block->getBlockDecl()->getBody());
12841     }
12842 
12843     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
12844       if (Capturer) return;
12845       if (OVE->getSourceExpr())
12846         Visit(OVE->getSourceExpr());
12847     }
12848 
12849     void VisitBinaryOperator(BinaryOperator *BinOp) {
12850       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
12851         return;
12852       Expr *LHS = BinOp->getLHS();
12853       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
12854         if (DRE->getDecl() != Variable)
12855           return;
12856         if (Expr *RHS = BinOp->getRHS()) {
12857           RHS = RHS->IgnoreParenCasts();
12858           llvm::APSInt Value;
12859           VarWillBeReased =
12860             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
12861         }
12862       }
12863     }
12864   };
12865 
12866 } // namespace
12867 
12868 /// Check whether the given argument is a block which captures a
12869 /// variable.
12870 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
12871   assert(owner.Variable && owner.Loc.isValid());
12872 
12873   e = e->IgnoreParenCasts();
12874 
12875   // Look through [^{...} copy] and Block_copy(^{...}).
12876   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
12877     Selector Cmd = ME->getSelector();
12878     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
12879       e = ME->getInstanceReceiver();
12880       if (!e)
12881         return nullptr;
12882       e = e->IgnoreParenCasts();
12883     }
12884   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
12885     if (CE->getNumArgs() == 1) {
12886       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
12887       if (Fn) {
12888         const IdentifierInfo *FnI = Fn->getIdentifier();
12889         if (FnI && FnI->isStr("_Block_copy")) {
12890           e = CE->getArg(0)->IgnoreParenCasts();
12891         }
12892       }
12893     }
12894   }
12895 
12896   BlockExpr *block = dyn_cast<BlockExpr>(e);
12897   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
12898     return nullptr;
12899 
12900   FindCaptureVisitor visitor(S.Context, owner.Variable);
12901   visitor.Visit(block->getBlockDecl()->getBody());
12902   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
12903 }
12904 
12905 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
12906                                 RetainCycleOwner &owner) {
12907   assert(capturer);
12908   assert(owner.Variable && owner.Loc.isValid());
12909 
12910   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
12911     << owner.Variable << capturer->getSourceRange();
12912   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
12913     << owner.Indirect << owner.Range;
12914 }
12915 
12916 /// Check for a keyword selector that starts with the word 'add' or
12917 /// 'set'.
12918 static bool isSetterLikeSelector(Selector sel) {
12919   if (sel.isUnarySelector()) return false;
12920 
12921   StringRef str = sel.getNameForSlot(0);
12922   while (!str.empty() && str.front() == '_') str = str.substr(1);
12923   if (str.startswith("set"))
12924     str = str.substr(3);
12925   else if (str.startswith("add")) {
12926     // Specially whitelist 'addOperationWithBlock:'.
12927     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
12928       return false;
12929     str = str.substr(3);
12930   }
12931   else
12932     return false;
12933 
12934   if (str.empty()) return true;
12935   return !isLowercase(str.front());
12936 }
12937 
12938 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
12939                                                     ObjCMessageExpr *Message) {
12940   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
12941                                                 Message->getReceiverInterface(),
12942                                                 NSAPI::ClassId_NSMutableArray);
12943   if (!IsMutableArray) {
12944     return None;
12945   }
12946 
12947   Selector Sel = Message->getSelector();
12948 
12949   Optional<NSAPI::NSArrayMethodKind> MKOpt =
12950     S.NSAPIObj->getNSArrayMethodKind(Sel);
12951   if (!MKOpt) {
12952     return None;
12953   }
12954 
12955   NSAPI::NSArrayMethodKind MK = *MKOpt;
12956 
12957   switch (MK) {
12958     case NSAPI::NSMutableArr_addObject:
12959     case NSAPI::NSMutableArr_insertObjectAtIndex:
12960     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
12961       return 0;
12962     case NSAPI::NSMutableArr_replaceObjectAtIndex:
12963       return 1;
12964 
12965     default:
12966       return None;
12967   }
12968 
12969   return None;
12970 }
12971 
12972 static
12973 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
12974                                                   ObjCMessageExpr *Message) {
12975   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
12976                                             Message->getReceiverInterface(),
12977                                             NSAPI::ClassId_NSMutableDictionary);
12978   if (!IsMutableDictionary) {
12979     return None;
12980   }
12981 
12982   Selector Sel = Message->getSelector();
12983 
12984   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
12985     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
12986   if (!MKOpt) {
12987     return None;
12988   }
12989 
12990   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
12991 
12992   switch (MK) {
12993     case NSAPI::NSMutableDict_setObjectForKey:
12994     case NSAPI::NSMutableDict_setValueForKey:
12995     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
12996       return 0;
12997 
12998     default:
12999       return None;
13000   }
13001 
13002   return None;
13003 }
13004 
13005 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
13006   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
13007                                                 Message->getReceiverInterface(),
13008                                                 NSAPI::ClassId_NSMutableSet);
13009 
13010   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
13011                                             Message->getReceiverInterface(),
13012                                             NSAPI::ClassId_NSMutableOrderedSet);
13013   if (!IsMutableSet && !IsMutableOrderedSet) {
13014     return None;
13015   }
13016 
13017   Selector Sel = Message->getSelector();
13018 
13019   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
13020   if (!MKOpt) {
13021     return None;
13022   }
13023 
13024   NSAPI::NSSetMethodKind MK = *MKOpt;
13025 
13026   switch (MK) {
13027     case NSAPI::NSMutableSet_addObject:
13028     case NSAPI::NSOrderedSet_setObjectAtIndex:
13029     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
13030     case NSAPI::NSOrderedSet_insertObjectAtIndex:
13031       return 0;
13032     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
13033       return 1;
13034   }
13035 
13036   return None;
13037 }
13038 
13039 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
13040   if (!Message->isInstanceMessage()) {
13041     return;
13042   }
13043 
13044   Optional<int> ArgOpt;
13045 
13046   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
13047       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
13048       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
13049     return;
13050   }
13051 
13052   int ArgIndex = *ArgOpt;
13053 
13054   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
13055   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
13056     Arg = OE->getSourceExpr()->IgnoreImpCasts();
13057   }
13058 
13059   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
13060     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13061       if (ArgRE->isObjCSelfExpr()) {
13062         Diag(Message->getSourceRange().getBegin(),
13063              diag::warn_objc_circular_container)
13064           << ArgRE->getDecl() << StringRef("'super'");
13065       }
13066     }
13067   } else {
13068     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
13069 
13070     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
13071       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
13072     }
13073 
13074     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
13075       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
13076         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
13077           ValueDecl *Decl = ReceiverRE->getDecl();
13078           Diag(Message->getSourceRange().getBegin(),
13079                diag::warn_objc_circular_container)
13080             << Decl << Decl;
13081           if (!ArgRE->isObjCSelfExpr()) {
13082             Diag(Decl->getLocation(),
13083                  diag::note_objc_circular_container_declared_here)
13084               << Decl;
13085           }
13086         }
13087       }
13088     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
13089       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
13090         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
13091           ObjCIvarDecl *Decl = IvarRE->getDecl();
13092           Diag(Message->getSourceRange().getBegin(),
13093                diag::warn_objc_circular_container)
13094             << Decl << Decl;
13095           Diag(Decl->getLocation(),
13096                diag::note_objc_circular_container_declared_here)
13097             << Decl;
13098         }
13099       }
13100     }
13101   }
13102 }
13103 
13104 /// Check a message send to see if it's likely to cause a retain cycle.
13105 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
13106   // Only check instance methods whose selector looks like a setter.
13107   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
13108     return;
13109 
13110   // Try to find a variable that the receiver is strongly owned by.
13111   RetainCycleOwner owner;
13112   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
13113     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
13114       return;
13115   } else {
13116     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
13117     owner.Variable = getCurMethodDecl()->getSelfDecl();
13118     owner.Loc = msg->getSuperLoc();
13119     owner.Range = msg->getSuperLoc();
13120   }
13121 
13122   // Check whether the receiver is captured by any of the arguments.
13123   const ObjCMethodDecl *MD = msg->getMethodDecl();
13124   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
13125     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
13126       // noescape blocks should not be retained by the method.
13127       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
13128         continue;
13129       return diagnoseRetainCycle(*this, capturer, owner);
13130     }
13131   }
13132 }
13133 
13134 /// Check a property assign to see if it's likely to cause a retain cycle.
13135 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
13136   RetainCycleOwner owner;
13137   if (!findRetainCycleOwner(*this, receiver, owner))
13138     return;
13139 
13140   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
13141     diagnoseRetainCycle(*this, capturer, owner);
13142 }
13143 
13144 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
13145   RetainCycleOwner Owner;
13146   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
13147     return;
13148 
13149   // Because we don't have an expression for the variable, we have to set the
13150   // location explicitly here.
13151   Owner.Loc = Var->getLocation();
13152   Owner.Range = Var->getSourceRange();
13153 
13154   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
13155     diagnoseRetainCycle(*this, Capturer, Owner);
13156 }
13157 
13158 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
13159                                      Expr *RHS, bool isProperty) {
13160   // Check if RHS is an Objective-C object literal, which also can get
13161   // immediately zapped in a weak reference.  Note that we explicitly
13162   // allow ObjCStringLiterals, since those are designed to never really die.
13163   RHS = RHS->IgnoreParenImpCasts();
13164 
13165   // This enum needs to match with the 'select' in
13166   // warn_objc_arc_literal_assign (off-by-1).
13167   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
13168   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
13169     return false;
13170 
13171   S.Diag(Loc, diag::warn_arc_literal_assign)
13172     << (unsigned) Kind
13173     << (isProperty ? 0 : 1)
13174     << RHS->getSourceRange();
13175 
13176   return true;
13177 }
13178 
13179 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
13180                                     Qualifiers::ObjCLifetime LT,
13181                                     Expr *RHS, bool isProperty) {
13182   // Strip off any implicit cast added to get to the one ARC-specific.
13183   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13184     if (cast->getCastKind() == CK_ARCConsumeObject) {
13185       S.Diag(Loc, diag::warn_arc_retained_assign)
13186         << (LT == Qualifiers::OCL_ExplicitNone)
13187         << (isProperty ? 0 : 1)
13188         << RHS->getSourceRange();
13189       return true;
13190     }
13191     RHS = cast->getSubExpr();
13192   }
13193 
13194   if (LT == Qualifiers::OCL_Weak &&
13195       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
13196     return true;
13197 
13198   return false;
13199 }
13200 
13201 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
13202                               QualType LHS, Expr *RHS) {
13203   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
13204 
13205   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
13206     return false;
13207 
13208   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
13209     return true;
13210 
13211   return false;
13212 }
13213 
13214 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
13215                               Expr *LHS, Expr *RHS) {
13216   QualType LHSType;
13217   // PropertyRef on LHS type need be directly obtained from
13218   // its declaration as it has a PseudoType.
13219   ObjCPropertyRefExpr *PRE
13220     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
13221   if (PRE && !PRE->isImplicitProperty()) {
13222     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13223     if (PD)
13224       LHSType = PD->getType();
13225   }
13226 
13227   if (LHSType.isNull())
13228     LHSType = LHS->getType();
13229 
13230   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
13231 
13232   if (LT == Qualifiers::OCL_Weak) {
13233     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
13234       getCurFunction()->markSafeWeakUse(LHS);
13235   }
13236 
13237   if (checkUnsafeAssigns(Loc, LHSType, RHS))
13238     return;
13239 
13240   // FIXME. Check for other life times.
13241   if (LT != Qualifiers::OCL_None)
13242     return;
13243 
13244   if (PRE) {
13245     if (PRE->isImplicitProperty())
13246       return;
13247     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
13248     if (!PD)
13249       return;
13250 
13251     unsigned Attributes = PD->getPropertyAttributes();
13252     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
13253       // when 'assign' attribute was not explicitly specified
13254       // by user, ignore it and rely on property type itself
13255       // for lifetime info.
13256       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
13257       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
13258           LHSType->isObjCRetainableType())
13259         return;
13260 
13261       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
13262         if (cast->getCastKind() == CK_ARCConsumeObject) {
13263           Diag(Loc, diag::warn_arc_retained_property_assign)
13264           << RHS->getSourceRange();
13265           return;
13266         }
13267         RHS = cast->getSubExpr();
13268       }
13269     }
13270     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
13271       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
13272         return;
13273     }
13274   }
13275 }
13276 
13277 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
13278 
13279 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
13280                                         SourceLocation StmtLoc,
13281                                         const NullStmt *Body) {
13282   // Do not warn if the body is a macro that expands to nothing, e.g:
13283   //
13284   // #define CALL(x)
13285   // if (condition)
13286   //   CALL(0);
13287   if (Body->hasLeadingEmptyMacro())
13288     return false;
13289 
13290   // Get line numbers of statement and body.
13291   bool StmtLineInvalid;
13292   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
13293                                                       &StmtLineInvalid);
13294   if (StmtLineInvalid)
13295     return false;
13296 
13297   bool BodyLineInvalid;
13298   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
13299                                                       &BodyLineInvalid);
13300   if (BodyLineInvalid)
13301     return false;
13302 
13303   // Warn if null statement and body are on the same line.
13304   if (StmtLine != BodyLine)
13305     return false;
13306 
13307   return true;
13308 }
13309 
13310 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
13311                                  const Stmt *Body,
13312                                  unsigned DiagID) {
13313   // Since this is a syntactic check, don't emit diagnostic for template
13314   // instantiations, this just adds noise.
13315   if (CurrentInstantiationScope)
13316     return;
13317 
13318   // The body should be a null statement.
13319   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13320   if (!NBody)
13321     return;
13322 
13323   // Do the usual checks.
13324   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13325     return;
13326 
13327   Diag(NBody->getSemiLoc(), DiagID);
13328   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13329 }
13330 
13331 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
13332                                  const Stmt *PossibleBody) {
13333   assert(!CurrentInstantiationScope); // Ensured by caller
13334 
13335   SourceLocation StmtLoc;
13336   const Stmt *Body;
13337   unsigned DiagID;
13338   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
13339     StmtLoc = FS->getRParenLoc();
13340     Body = FS->getBody();
13341     DiagID = diag::warn_empty_for_body;
13342   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
13343     StmtLoc = WS->getCond()->getSourceRange().getEnd();
13344     Body = WS->getBody();
13345     DiagID = diag::warn_empty_while_body;
13346   } else
13347     return; // Neither `for' nor `while'.
13348 
13349   // The body should be a null statement.
13350   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
13351   if (!NBody)
13352     return;
13353 
13354   // Skip expensive checks if diagnostic is disabled.
13355   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
13356     return;
13357 
13358   // Do the usual checks.
13359   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
13360     return;
13361 
13362   // `for(...);' and `while(...);' are popular idioms, so in order to keep
13363   // noise level low, emit diagnostics only if for/while is followed by a
13364   // CompoundStmt, e.g.:
13365   //    for (int i = 0; i < n; i++);
13366   //    {
13367   //      a(i);
13368   //    }
13369   // or if for/while is followed by a statement with more indentation
13370   // than for/while itself:
13371   //    for (int i = 0; i < n; i++);
13372   //      a(i);
13373   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
13374   if (!ProbableTypo) {
13375     bool BodyColInvalid;
13376     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
13377         PossibleBody->getBeginLoc(), &BodyColInvalid);
13378     if (BodyColInvalid)
13379       return;
13380 
13381     bool StmtColInvalid;
13382     unsigned StmtCol =
13383         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
13384     if (StmtColInvalid)
13385       return;
13386 
13387     if (BodyCol > StmtCol)
13388       ProbableTypo = true;
13389   }
13390 
13391   if (ProbableTypo) {
13392     Diag(NBody->getSemiLoc(), DiagID);
13393     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
13394   }
13395 }
13396 
13397 //===--- CHECK: Warn on self move with std::move. -------------------------===//
13398 
13399 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
13400 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
13401                              SourceLocation OpLoc) {
13402   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
13403     return;
13404 
13405   if (inTemplateInstantiation())
13406     return;
13407 
13408   // Strip parens and casts away.
13409   LHSExpr = LHSExpr->IgnoreParenImpCasts();
13410   RHSExpr = RHSExpr->IgnoreParenImpCasts();
13411 
13412   // Check for a call expression
13413   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
13414   if (!CE || CE->getNumArgs() != 1)
13415     return;
13416 
13417   // Check for a call to std::move
13418   if (!CE->isCallToStdMove())
13419     return;
13420 
13421   // Get argument from std::move
13422   RHSExpr = CE->getArg(0);
13423 
13424   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
13425   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
13426 
13427   // Two DeclRefExpr's, check that the decls are the same.
13428   if (LHSDeclRef && RHSDeclRef) {
13429     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13430       return;
13431     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13432         RHSDeclRef->getDecl()->getCanonicalDecl())
13433       return;
13434 
13435     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13436                                         << LHSExpr->getSourceRange()
13437                                         << RHSExpr->getSourceRange();
13438     return;
13439   }
13440 
13441   // Member variables require a different approach to check for self moves.
13442   // MemberExpr's are the same if every nested MemberExpr refers to the same
13443   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
13444   // the base Expr's are CXXThisExpr's.
13445   const Expr *LHSBase = LHSExpr;
13446   const Expr *RHSBase = RHSExpr;
13447   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
13448   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
13449   if (!LHSME || !RHSME)
13450     return;
13451 
13452   while (LHSME && RHSME) {
13453     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
13454         RHSME->getMemberDecl()->getCanonicalDecl())
13455       return;
13456 
13457     LHSBase = LHSME->getBase();
13458     RHSBase = RHSME->getBase();
13459     LHSME = dyn_cast<MemberExpr>(LHSBase);
13460     RHSME = dyn_cast<MemberExpr>(RHSBase);
13461   }
13462 
13463   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
13464   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
13465   if (LHSDeclRef && RHSDeclRef) {
13466     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
13467       return;
13468     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
13469         RHSDeclRef->getDecl()->getCanonicalDecl())
13470       return;
13471 
13472     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13473                                         << LHSExpr->getSourceRange()
13474                                         << RHSExpr->getSourceRange();
13475     return;
13476   }
13477 
13478   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
13479     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
13480                                         << LHSExpr->getSourceRange()
13481                                         << RHSExpr->getSourceRange();
13482 }
13483 
13484 //===--- Layout compatibility ----------------------------------------------//
13485 
13486 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
13487 
13488 /// Check if two enumeration types are layout-compatible.
13489 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
13490   // C++11 [dcl.enum] p8:
13491   // Two enumeration types are layout-compatible if they have the same
13492   // underlying type.
13493   return ED1->isComplete() && ED2->isComplete() &&
13494          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
13495 }
13496 
13497 /// Check if two fields are layout-compatible.
13498 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
13499                                FieldDecl *Field2) {
13500   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
13501     return false;
13502 
13503   if (Field1->isBitField() != Field2->isBitField())
13504     return false;
13505 
13506   if (Field1->isBitField()) {
13507     // Make sure that the bit-fields are the same length.
13508     unsigned Bits1 = Field1->getBitWidthValue(C);
13509     unsigned Bits2 = Field2->getBitWidthValue(C);
13510 
13511     if (Bits1 != Bits2)
13512       return false;
13513   }
13514 
13515   return true;
13516 }
13517 
13518 /// Check if two standard-layout structs are layout-compatible.
13519 /// (C++11 [class.mem] p17)
13520 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
13521                                      RecordDecl *RD2) {
13522   // If both records are C++ classes, check that base classes match.
13523   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
13524     // If one of records is a CXXRecordDecl we are in C++ mode,
13525     // thus the other one is a CXXRecordDecl, too.
13526     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
13527     // Check number of base classes.
13528     if (D1CXX->getNumBases() != D2CXX->getNumBases())
13529       return false;
13530 
13531     // Check the base classes.
13532     for (CXXRecordDecl::base_class_const_iterator
13533                Base1 = D1CXX->bases_begin(),
13534            BaseEnd1 = D1CXX->bases_end(),
13535               Base2 = D2CXX->bases_begin();
13536          Base1 != BaseEnd1;
13537          ++Base1, ++Base2) {
13538       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
13539         return false;
13540     }
13541   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
13542     // If only RD2 is a C++ class, it should have zero base classes.
13543     if (D2CXX->getNumBases() > 0)
13544       return false;
13545   }
13546 
13547   // Check the fields.
13548   RecordDecl::field_iterator Field2 = RD2->field_begin(),
13549                              Field2End = RD2->field_end(),
13550                              Field1 = RD1->field_begin(),
13551                              Field1End = RD1->field_end();
13552   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
13553     if (!isLayoutCompatible(C, *Field1, *Field2))
13554       return false;
13555   }
13556   if (Field1 != Field1End || Field2 != Field2End)
13557     return false;
13558 
13559   return true;
13560 }
13561 
13562 /// Check if two standard-layout unions are layout-compatible.
13563 /// (C++11 [class.mem] p18)
13564 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
13565                                     RecordDecl *RD2) {
13566   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
13567   for (auto *Field2 : RD2->fields())
13568     UnmatchedFields.insert(Field2);
13569 
13570   for (auto *Field1 : RD1->fields()) {
13571     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
13572         I = UnmatchedFields.begin(),
13573         E = UnmatchedFields.end();
13574 
13575     for ( ; I != E; ++I) {
13576       if (isLayoutCompatible(C, Field1, *I)) {
13577         bool Result = UnmatchedFields.erase(*I);
13578         (void) Result;
13579         assert(Result);
13580         break;
13581       }
13582     }
13583     if (I == E)
13584       return false;
13585   }
13586 
13587   return UnmatchedFields.empty();
13588 }
13589 
13590 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
13591                                RecordDecl *RD2) {
13592   if (RD1->isUnion() != RD2->isUnion())
13593     return false;
13594 
13595   if (RD1->isUnion())
13596     return isLayoutCompatibleUnion(C, RD1, RD2);
13597   else
13598     return isLayoutCompatibleStruct(C, RD1, RD2);
13599 }
13600 
13601 /// Check if two types are layout-compatible in C++11 sense.
13602 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
13603   if (T1.isNull() || T2.isNull())
13604     return false;
13605 
13606   // C++11 [basic.types] p11:
13607   // If two types T1 and T2 are the same type, then T1 and T2 are
13608   // layout-compatible types.
13609   if (C.hasSameType(T1, T2))
13610     return true;
13611 
13612   T1 = T1.getCanonicalType().getUnqualifiedType();
13613   T2 = T2.getCanonicalType().getUnqualifiedType();
13614 
13615   const Type::TypeClass TC1 = T1->getTypeClass();
13616   const Type::TypeClass TC2 = T2->getTypeClass();
13617 
13618   if (TC1 != TC2)
13619     return false;
13620 
13621   if (TC1 == Type::Enum) {
13622     return isLayoutCompatible(C,
13623                               cast<EnumType>(T1)->getDecl(),
13624                               cast<EnumType>(T2)->getDecl());
13625   } else if (TC1 == Type::Record) {
13626     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
13627       return false;
13628 
13629     return isLayoutCompatible(C,
13630                               cast<RecordType>(T1)->getDecl(),
13631                               cast<RecordType>(T2)->getDecl());
13632   }
13633 
13634   return false;
13635 }
13636 
13637 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
13638 
13639 /// Given a type tag expression find the type tag itself.
13640 ///
13641 /// \param TypeExpr Type tag expression, as it appears in user's code.
13642 ///
13643 /// \param VD Declaration of an identifier that appears in a type tag.
13644 ///
13645 /// \param MagicValue Type tag magic value.
13646 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
13647                             const ValueDecl **VD, uint64_t *MagicValue) {
13648   while(true) {
13649     if (!TypeExpr)
13650       return false;
13651 
13652     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
13653 
13654     switch (TypeExpr->getStmtClass()) {
13655     case Stmt::UnaryOperatorClass: {
13656       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
13657       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
13658         TypeExpr = UO->getSubExpr();
13659         continue;
13660       }
13661       return false;
13662     }
13663 
13664     case Stmt::DeclRefExprClass: {
13665       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
13666       *VD = DRE->getDecl();
13667       return true;
13668     }
13669 
13670     case Stmt::IntegerLiteralClass: {
13671       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
13672       llvm::APInt MagicValueAPInt = IL->getValue();
13673       if (MagicValueAPInt.getActiveBits() <= 64) {
13674         *MagicValue = MagicValueAPInt.getZExtValue();
13675         return true;
13676       } else
13677         return false;
13678     }
13679 
13680     case Stmt::BinaryConditionalOperatorClass:
13681     case Stmt::ConditionalOperatorClass: {
13682       const AbstractConditionalOperator *ACO =
13683           cast<AbstractConditionalOperator>(TypeExpr);
13684       bool Result;
13685       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
13686         if (Result)
13687           TypeExpr = ACO->getTrueExpr();
13688         else
13689           TypeExpr = ACO->getFalseExpr();
13690         continue;
13691       }
13692       return false;
13693     }
13694 
13695     case Stmt::BinaryOperatorClass: {
13696       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
13697       if (BO->getOpcode() == BO_Comma) {
13698         TypeExpr = BO->getRHS();
13699         continue;
13700       }
13701       return false;
13702     }
13703 
13704     default:
13705       return false;
13706     }
13707   }
13708 }
13709 
13710 /// Retrieve the C type corresponding to type tag TypeExpr.
13711 ///
13712 /// \param TypeExpr Expression that specifies a type tag.
13713 ///
13714 /// \param MagicValues Registered magic values.
13715 ///
13716 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
13717 ///        kind.
13718 ///
13719 /// \param TypeInfo Information about the corresponding C type.
13720 ///
13721 /// \returns true if the corresponding C type was found.
13722 static bool GetMatchingCType(
13723         const IdentifierInfo *ArgumentKind,
13724         const Expr *TypeExpr, const ASTContext &Ctx,
13725         const llvm::DenseMap<Sema::TypeTagMagicValue,
13726                              Sema::TypeTagData> *MagicValues,
13727         bool &FoundWrongKind,
13728         Sema::TypeTagData &TypeInfo) {
13729   FoundWrongKind = false;
13730 
13731   // Variable declaration that has type_tag_for_datatype attribute.
13732   const ValueDecl *VD = nullptr;
13733 
13734   uint64_t MagicValue;
13735 
13736   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
13737     return false;
13738 
13739   if (VD) {
13740     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
13741       if (I->getArgumentKind() != ArgumentKind) {
13742         FoundWrongKind = true;
13743         return false;
13744       }
13745       TypeInfo.Type = I->getMatchingCType();
13746       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
13747       TypeInfo.MustBeNull = I->getMustBeNull();
13748       return true;
13749     }
13750     return false;
13751   }
13752 
13753   if (!MagicValues)
13754     return false;
13755 
13756   llvm::DenseMap<Sema::TypeTagMagicValue,
13757                  Sema::TypeTagData>::const_iterator I =
13758       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
13759   if (I == MagicValues->end())
13760     return false;
13761 
13762   TypeInfo = I->second;
13763   return true;
13764 }
13765 
13766 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13767                                       uint64_t MagicValue, QualType Type,
13768                                       bool LayoutCompatible,
13769                                       bool MustBeNull) {
13770   if (!TypeTagForDatatypeMagicValues)
13771     TypeTagForDatatypeMagicValues.reset(
13772         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
13773 
13774   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
13775   (*TypeTagForDatatypeMagicValues)[Magic] =
13776       TypeTagData(Type, LayoutCompatible, MustBeNull);
13777 }
13778 
13779 static bool IsSameCharType(QualType T1, QualType T2) {
13780   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
13781   if (!BT1)
13782     return false;
13783 
13784   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
13785   if (!BT2)
13786     return false;
13787 
13788   BuiltinType::Kind T1Kind = BT1->getKind();
13789   BuiltinType::Kind T2Kind = BT2->getKind();
13790 
13791   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
13792          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
13793          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
13794          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
13795 }
13796 
13797 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13798                                     const ArrayRef<const Expr *> ExprArgs,
13799                                     SourceLocation CallSiteLoc) {
13800   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
13801   bool IsPointerAttr = Attr->getIsPointer();
13802 
13803   // Retrieve the argument representing the 'type_tag'.
13804   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
13805   if (TypeTagIdxAST >= ExprArgs.size()) {
13806     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13807         << 0 << Attr->getTypeTagIdx().getSourceIndex();
13808     return;
13809   }
13810   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
13811   bool FoundWrongKind;
13812   TypeTagData TypeInfo;
13813   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
13814                         TypeTagForDatatypeMagicValues.get(),
13815                         FoundWrongKind, TypeInfo)) {
13816     if (FoundWrongKind)
13817       Diag(TypeTagExpr->getExprLoc(),
13818            diag::warn_type_tag_for_datatype_wrong_kind)
13819         << TypeTagExpr->getSourceRange();
13820     return;
13821   }
13822 
13823   // Retrieve the argument representing the 'arg_idx'.
13824   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
13825   if (ArgumentIdxAST >= ExprArgs.size()) {
13826     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
13827         << 1 << Attr->getArgumentIdx().getSourceIndex();
13828     return;
13829   }
13830   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
13831   if (IsPointerAttr) {
13832     // Skip implicit cast of pointer to `void *' (as a function argument).
13833     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
13834       if (ICE->getType()->isVoidPointerType() &&
13835           ICE->getCastKind() == CK_BitCast)
13836         ArgumentExpr = ICE->getSubExpr();
13837   }
13838   QualType ArgumentType = ArgumentExpr->getType();
13839 
13840   // Passing a `void*' pointer shouldn't trigger a warning.
13841   if (IsPointerAttr && ArgumentType->isVoidPointerType())
13842     return;
13843 
13844   if (TypeInfo.MustBeNull) {
13845     // Type tag with matching void type requires a null pointer.
13846     if (!ArgumentExpr->isNullPointerConstant(Context,
13847                                              Expr::NPC_ValueDependentIsNotNull)) {
13848       Diag(ArgumentExpr->getExprLoc(),
13849            diag::warn_type_safety_null_pointer_required)
13850           << ArgumentKind->getName()
13851           << ArgumentExpr->getSourceRange()
13852           << TypeTagExpr->getSourceRange();
13853     }
13854     return;
13855   }
13856 
13857   QualType RequiredType = TypeInfo.Type;
13858   if (IsPointerAttr)
13859     RequiredType = Context.getPointerType(RequiredType);
13860 
13861   bool mismatch = false;
13862   if (!TypeInfo.LayoutCompatible) {
13863     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
13864 
13865     // C++11 [basic.fundamental] p1:
13866     // Plain char, signed char, and unsigned char are three distinct types.
13867     //
13868     // But we treat plain `char' as equivalent to `signed char' or `unsigned
13869     // char' depending on the current char signedness mode.
13870     if (mismatch)
13871       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
13872                                            RequiredType->getPointeeType())) ||
13873           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
13874         mismatch = false;
13875   } else
13876     if (IsPointerAttr)
13877       mismatch = !isLayoutCompatible(Context,
13878                                      ArgumentType->getPointeeType(),
13879                                      RequiredType->getPointeeType());
13880     else
13881       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
13882 
13883   if (mismatch)
13884     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
13885         << ArgumentType << ArgumentKind
13886         << TypeInfo.LayoutCompatible << RequiredType
13887         << ArgumentExpr->getSourceRange()
13888         << TypeTagExpr->getSourceRange();
13889 }
13890 
13891 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13892                                          CharUnits Alignment) {
13893   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
13894 }
13895 
13896 void Sema::DiagnoseMisalignedMembers() {
13897   for (MisalignedMember &m : MisalignedMembers) {
13898     const NamedDecl *ND = m.RD;
13899     if (ND->getName().empty()) {
13900       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
13901         ND = TD;
13902     }
13903     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
13904         << m.MD << ND << m.E->getSourceRange();
13905   }
13906   MisalignedMembers.clear();
13907 }
13908 
13909 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
13910   E = E->IgnoreParens();
13911   if (!T->isPointerType() && !T->isIntegerType())
13912     return;
13913   if (isa<UnaryOperator>(E) &&
13914       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
13915     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
13916     if (isa<MemberExpr>(Op)) {
13917       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
13918                           MisalignedMember(Op));
13919       if (MA != MisalignedMembers.end() &&
13920           (T->isIntegerType() ||
13921            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
13922                                    Context.getTypeAlignInChars(
13923                                        T->getPointeeType()) <= MA->Alignment))))
13924         MisalignedMembers.erase(MA);
13925     }
13926   }
13927 }
13928 
13929 void Sema::RefersToMemberWithReducedAlignment(
13930     Expr *E,
13931     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13932         Action) {
13933   const auto *ME = dyn_cast<MemberExpr>(E);
13934   if (!ME)
13935     return;
13936 
13937   // No need to check expressions with an __unaligned-qualified type.
13938   if (E->getType().getQualifiers().hasUnaligned())
13939     return;
13940 
13941   // For a chain of MemberExpr like "a.b.c.d" this list
13942   // will keep FieldDecl's like [d, c, b].
13943   SmallVector<FieldDecl *, 4> ReverseMemberChain;
13944   const MemberExpr *TopME = nullptr;
13945   bool AnyIsPacked = false;
13946   do {
13947     QualType BaseType = ME->getBase()->getType();
13948     if (ME->isArrow())
13949       BaseType = BaseType->getPointeeType();
13950     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
13951     if (RD->isInvalidDecl())
13952       return;
13953 
13954     ValueDecl *MD = ME->getMemberDecl();
13955     auto *FD = dyn_cast<FieldDecl>(MD);
13956     // We do not care about non-data members.
13957     if (!FD || FD->isInvalidDecl())
13958       return;
13959 
13960     AnyIsPacked =
13961         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
13962     ReverseMemberChain.push_back(FD);
13963 
13964     TopME = ME;
13965     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
13966   } while (ME);
13967   assert(TopME && "We did not compute a topmost MemberExpr!");
13968 
13969   // Not the scope of this diagnostic.
13970   if (!AnyIsPacked)
13971     return;
13972 
13973   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
13974   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
13975   // TODO: The innermost base of the member expression may be too complicated.
13976   // For now, just disregard these cases. This is left for future
13977   // improvement.
13978   if (!DRE && !isa<CXXThisExpr>(TopBase))
13979       return;
13980 
13981   // Alignment expected by the whole expression.
13982   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
13983 
13984   // No need to do anything else with this case.
13985   if (ExpectedAlignment.isOne())
13986     return;
13987 
13988   // Synthesize offset of the whole access.
13989   CharUnits Offset;
13990   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
13991        I++) {
13992     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
13993   }
13994 
13995   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
13996   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
13997       ReverseMemberChain.back()->getParent()->getTypeForDecl());
13998 
13999   // The base expression of the innermost MemberExpr may give
14000   // stronger guarantees than the class containing the member.
14001   if (DRE && !TopME->isArrow()) {
14002     const ValueDecl *VD = DRE->getDecl();
14003     if (!VD->getType()->isReferenceType())
14004       CompleteObjectAlignment =
14005           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
14006   }
14007 
14008   // Check if the synthesized offset fulfills the alignment.
14009   if (Offset % ExpectedAlignment != 0 ||
14010       // It may fulfill the offset it but the effective alignment may still be
14011       // lower than the expected expression alignment.
14012       CompleteObjectAlignment < ExpectedAlignment) {
14013     // If this happens, we want to determine a sensible culprit of this.
14014     // Intuitively, watching the chain of member expressions from right to
14015     // left, we start with the required alignment (as required by the field
14016     // type) but some packed attribute in that chain has reduced the alignment.
14017     // It may happen that another packed structure increases it again. But if
14018     // we are here such increase has not been enough. So pointing the first
14019     // FieldDecl that either is packed or else its RecordDecl is,
14020     // seems reasonable.
14021     FieldDecl *FD = nullptr;
14022     CharUnits Alignment;
14023     for (FieldDecl *FDI : ReverseMemberChain) {
14024       if (FDI->hasAttr<PackedAttr>() ||
14025           FDI->getParent()->hasAttr<PackedAttr>()) {
14026         FD = FDI;
14027         Alignment = std::min(
14028             Context.getTypeAlignInChars(FD->getType()),
14029             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
14030         break;
14031       }
14032     }
14033     assert(FD && "We did not find a packed FieldDecl!");
14034     Action(E, FD->getParent(), FD, Alignment);
14035   }
14036 }
14037 
14038 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
14039   using namespace std::placeholders;
14040 
14041   RefersToMemberWithReducedAlignment(
14042       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
14043                      _2, _3, _4));
14044 }
14045