1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements extra semantic analysis beyond what is enforced
11 //  by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/APValue.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclarationName.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/Expr.h"
27 #include "clang/AST/ExprCXX.h"
28 #include "clang/AST/ExprObjC.h"
29 #include "clang/AST/ExprOpenMP.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/OperationKinds.h"
32 #include "clang/AST/Stmt.h"
33 #include "clang/AST/TemplateBase.h"
34 #include "clang/AST/Type.h"
35 #include "clang/AST/TypeLoc.h"
36 #include "clang/AST/UnresolvedSet.h"
37 #include "clang/Analysis/Analyses/FormatString.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->getLocEnd(), 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)->getLocStart(),
120                     call->getArg(argCount - 1)->getLocEnd());
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->getLocStart(), 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->getLocStart(), 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->getLocEnd(), 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->getLocStart(), 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->getLocStart());
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     Expr *Arg = TheCall->getArg(I);
200     QualType Ty = Arg->getType();
201     if (!Ty->isIntegerType()) {
202       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
203           << Ty << Arg->getSourceRange();
204       return true;
205     }
206   }
207 
208   // Third argument should be a pointer to a non-const integer.
209   // IRGen correctly handles volatile, restrict, and address spaces, and
210   // the other qualifiers aren't possible.
211   {
212     Expr *Arg = TheCall->getArg(2);
213     QualType Ty = Arg->getType();
214     const auto *PtrTy = Ty->getAs<PointerType>();
215     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
216           !PtrTy->getPointeeType().isConstQualified())) {
217       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
218           << Ty << Arg->getSourceRange();
219       return true;
220     }
221   }
222 
223   return false;
224 }
225 
226 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
227 		                  CallExpr *TheCall, unsigned SizeIdx,
228                                   unsigned DstSizeIdx) {
229   if (TheCall->getNumArgs() <= SizeIdx ||
230       TheCall->getNumArgs() <= DstSizeIdx)
231     return;
232 
233   const Expr *SizeArg = TheCall->getArg(SizeIdx);
234   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
235 
236   llvm::APSInt Size, DstSize;
237 
238   // find out if both sizes are known at compile time
239   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
240       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
241     return;
242 
243   if (Size.ule(DstSize))
244     return;
245 
246   // confirmed overflow so generate the diagnostic.
247   IdentifierInfo *FnName = FDecl->getIdentifier();
248   SourceLocation SL = TheCall->getLocStart();
249   SourceRange SR = TheCall->getSourceRange();
250 
251   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
252 }
253 
254 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
255   if (checkArgCount(S, BuiltinCall, 2))
256     return true;
257 
258   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
259   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
260   Expr *Call = BuiltinCall->getArg(0);
261   Expr *Chain = BuiltinCall->getArg(1);
262 
263   if (Call->getStmtClass() != Stmt::CallExprClass) {
264     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
265         << Call->getSourceRange();
266     return true;
267   }
268 
269   auto CE = cast<CallExpr>(Call);
270   if (CE->getCallee()->getType()->isBlockPointerType()) {
271     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
272         << Call->getSourceRange();
273     return true;
274   }
275 
276   const Decl *TargetDecl = CE->getCalleeDecl();
277   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
278     if (FD->getBuiltinID()) {
279       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
280           << Call->getSourceRange();
281       return true;
282     }
283 
284   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
285     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
286         << Call->getSourceRange();
287     return true;
288   }
289 
290   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
291   if (ChainResult.isInvalid())
292     return true;
293   if (!ChainResult.get()->getType()->isPointerType()) {
294     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
295         << Chain->getSourceRange();
296     return true;
297   }
298 
299   QualType ReturnTy = CE->getCallReturnType(S.Context);
300   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
301   QualType BuiltinTy = S.Context.getFunctionType(
302       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
303   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
304 
305   Builtin =
306       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
307 
308   BuiltinCall->setType(CE->getType());
309   BuiltinCall->setValueKind(CE->getValueKind());
310   BuiltinCall->setObjectKind(CE->getObjectKind());
311   BuiltinCall->setCallee(Builtin);
312   BuiltinCall->setArg(1, ChainResult.get());
313 
314   return false;
315 }
316 
317 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
318                                      Scope::ScopeFlags NeededScopeFlags,
319                                      unsigned DiagID) {
320   // Scopes aren't available during instantiation. Fortunately, builtin
321   // functions cannot be template args so they cannot be formed through template
322   // instantiation. Therefore checking once during the parse is sufficient.
323   if (SemaRef.inTemplateInstantiation())
324     return false;
325 
326   Scope *S = SemaRef.getCurScope();
327   while (S && !S->isSEHExceptScope())
328     S = S->getParent();
329   if (!S || !(S->getFlags() & NeededScopeFlags)) {
330     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
331     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
332         << DRE->getDecl()->getIdentifier();
333     return true;
334   }
335 
336   return false;
337 }
338 
339 static inline bool isBlockPointer(Expr *Arg) {
340   return Arg->getType()->isBlockPointerType();
341 }
342 
343 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
344 /// void*, which is a requirement of device side enqueue.
345 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
346   const BlockPointerType *BPT =
347       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
348   ArrayRef<QualType> Params =
349       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
350   unsigned ArgCounter = 0;
351   bool IllegalParams = false;
352   // Iterate through the block parameters until either one is found that is not
353   // a local void*, or the block is valid.
354   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
355        I != E; ++I, ++ArgCounter) {
356     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
357         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
358             LangAS::opencl_local) {
359       // Get the location of the error. If a block literal has been passed
360       // (BlockExpr) then we can point straight to the offending argument,
361       // else we just point to the variable reference.
362       SourceLocation ErrorLoc;
363       if (isa<BlockExpr>(BlockArg)) {
364         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
365         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
366       } else if (isa<DeclRefExpr>(BlockArg)) {
367         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
368       }
369       S.Diag(ErrorLoc,
370              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
371       IllegalParams = true;
372     }
373   }
374 
375   return IllegalParams;
376 }
377 
378 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
379   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
380     S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
381           << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
382     return true;
383   }
384   return false;
385 }
386 
387 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
388   if (checkArgCount(S, TheCall, 2))
389     return true;
390 
391   if (checkOpenCLSubgroupExt(S, TheCall))
392     return true;
393 
394   // First argument is an ndrange_t type.
395   Expr *NDRangeArg = TheCall->getArg(0);
396   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
397     S.Diag(NDRangeArg->getLocStart(),
398            diag::err_opencl_builtin_expected_type)
399         << TheCall->getDirectCallee() << "'ndrange_t'";
400     return true;
401   }
402 
403   Expr *BlockArg = TheCall->getArg(1);
404   if (!isBlockPointer(BlockArg)) {
405     S.Diag(BlockArg->getLocStart(),
406            diag::err_opencl_builtin_expected_type)
407         << TheCall->getDirectCallee() << "block";
408     return true;
409   }
410   return checkOpenCLBlockArgs(S, BlockArg);
411 }
412 
413 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
414 /// get_kernel_work_group_size
415 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
416 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
417   if (checkArgCount(S, TheCall, 1))
418     return true;
419 
420   Expr *BlockArg = TheCall->getArg(0);
421   if (!isBlockPointer(BlockArg)) {
422     S.Diag(BlockArg->getLocStart(),
423            diag::err_opencl_builtin_expected_type)
424         << TheCall->getDirectCallee() << "block";
425     return true;
426   }
427   return checkOpenCLBlockArgs(S, BlockArg);
428 }
429 
430 /// Diagnose integer type and any valid implicit conversion to it.
431 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
432                                       const QualType &IntType);
433 
434 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
435                                             unsigned Start, unsigned End) {
436   bool IllegalParams = false;
437   for (unsigned I = Start; I <= End; ++I)
438     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
439                                               S.Context.getSizeType());
440   return IllegalParams;
441 }
442 
443 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
444 /// 'local void*' parameter of passed block.
445 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
446                                            Expr *BlockArg,
447                                            unsigned NumNonVarArgs) {
448   const BlockPointerType *BPT =
449       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
450   unsigned NumBlockParams =
451       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
452   unsigned TotalNumArgs = TheCall->getNumArgs();
453 
454   // For each argument passed to the block, a corresponding uint needs to
455   // be passed to describe the size of the local memory.
456   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
457     S.Diag(TheCall->getLocStart(),
458            diag::err_opencl_enqueue_kernel_local_size_args);
459     return true;
460   }
461 
462   // Check that the sizes of the local memory are specified by integers.
463   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
464                                          TotalNumArgs - 1);
465 }
466 
467 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
468 /// overload formats specified in Table 6.13.17.1.
469 /// int enqueue_kernel(queue_t queue,
470 ///                    kernel_enqueue_flags_t flags,
471 ///                    const ndrange_t ndrange,
472 ///                    void (^block)(void))
473 /// int enqueue_kernel(queue_t queue,
474 ///                    kernel_enqueue_flags_t flags,
475 ///                    const ndrange_t ndrange,
476 ///                    uint num_events_in_wait_list,
477 ///                    clk_event_t *event_wait_list,
478 ///                    clk_event_t *event_ret,
479 ///                    void (^block)(void))
480 /// int enqueue_kernel(queue_t queue,
481 ///                    kernel_enqueue_flags_t flags,
482 ///                    const ndrange_t ndrange,
483 ///                    void (^block)(local void*, ...),
484 ///                    uint size0, ...)
485 /// int enqueue_kernel(queue_t queue,
486 ///                    kernel_enqueue_flags_t flags,
487 ///                    const ndrange_t ndrange,
488 ///                    uint num_events_in_wait_list,
489 ///                    clk_event_t *event_wait_list,
490 ///                    clk_event_t *event_ret,
491 ///                    void (^block)(local void*, ...),
492 ///                    uint size0, ...)
493 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
494   unsigned NumArgs = TheCall->getNumArgs();
495 
496   if (NumArgs < 4) {
497     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
498     return true;
499   }
500 
501   Expr *Arg0 = TheCall->getArg(0);
502   Expr *Arg1 = TheCall->getArg(1);
503   Expr *Arg2 = TheCall->getArg(2);
504   Expr *Arg3 = TheCall->getArg(3);
505 
506   // First argument always needs to be a queue_t type.
507   if (!Arg0->getType()->isQueueT()) {
508     S.Diag(TheCall->getArg(0)->getLocStart(),
509            diag::err_opencl_builtin_expected_type)
510         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
511     return true;
512   }
513 
514   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
515   if (!Arg1->getType()->isIntegerType()) {
516     S.Diag(TheCall->getArg(1)->getLocStart(),
517            diag::err_opencl_builtin_expected_type)
518         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
519     return true;
520   }
521 
522   // Third argument is always an ndrange_t type.
523   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
524     S.Diag(TheCall->getArg(2)->getLocStart(),
525            diag::err_opencl_builtin_expected_type)
526         << TheCall->getDirectCallee() << "'ndrange_t'";
527     return true;
528   }
529 
530   // With four arguments, there is only one form that the function could be
531   // called in: no events and no variable arguments.
532   if (NumArgs == 4) {
533     // check that the last argument is the right block type.
534     if (!isBlockPointer(Arg3)) {
535       S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
536           << TheCall->getDirectCallee() << "block";
537       return true;
538     }
539     // we have a block type, check the prototype
540     const BlockPointerType *BPT =
541         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
542     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
543       S.Diag(Arg3->getLocStart(),
544              diag::err_opencl_enqueue_kernel_blocks_no_args);
545       return true;
546     }
547     return false;
548   }
549   // we can have block + varargs.
550   if (isBlockPointer(Arg3))
551     return (checkOpenCLBlockArgs(S, Arg3) ||
552             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
553   // last two cases with either exactly 7 args or 7 args and varargs.
554   if (NumArgs >= 7) {
555     // check common block argument.
556     Expr *Arg6 = TheCall->getArg(6);
557     if (!isBlockPointer(Arg6)) {
558       S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
559           << TheCall->getDirectCallee() << "block";
560       return true;
561     }
562     if (checkOpenCLBlockArgs(S, Arg6))
563       return true;
564 
565     // Forth argument has to be any integer type.
566     if (!Arg3->getType()->isIntegerType()) {
567       S.Diag(TheCall->getArg(3)->getLocStart(),
568              diag::err_opencl_builtin_expected_type)
569           << TheCall->getDirectCallee() << "integer";
570       return true;
571     }
572     // check remaining common arguments.
573     Expr *Arg4 = TheCall->getArg(4);
574     Expr *Arg5 = TheCall->getArg(5);
575 
576     // Fifth argument is always passed as a pointer to clk_event_t.
577     if (!Arg4->isNullPointerConstant(S.Context,
578                                      Expr::NPC_ValueDependentIsNotNull) &&
579         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
580       S.Diag(TheCall->getArg(4)->getLocStart(),
581              diag::err_opencl_builtin_expected_type)
582           << TheCall->getDirectCallee()
583           << S.Context.getPointerType(S.Context.OCLClkEventTy);
584       return true;
585     }
586 
587     // Sixth argument is always passed as a pointer to clk_event_t.
588     if (!Arg5->isNullPointerConstant(S.Context,
589                                      Expr::NPC_ValueDependentIsNotNull) &&
590         !(Arg5->getType()->isPointerType() &&
591           Arg5->getType()->getPointeeType()->isClkEventT())) {
592       S.Diag(TheCall->getArg(5)->getLocStart(),
593              diag::err_opencl_builtin_expected_type)
594           << TheCall->getDirectCallee()
595           << S.Context.getPointerType(S.Context.OCLClkEventTy);
596       return true;
597     }
598 
599     if (NumArgs == 7)
600       return false;
601 
602     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
603   }
604 
605   // None of the specific case has been detected, give generic error
606   S.Diag(TheCall->getLocStart(),
607          diag::err_opencl_enqueue_kernel_incorrect_args);
608   return true;
609 }
610 
611 /// Returns OpenCL access qual.
612 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
613     return D->getAttr<OpenCLAccessAttr>();
614 }
615 
616 /// Returns true if pipe element type is different from the pointer.
617 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
618   const Expr *Arg0 = Call->getArg(0);
619   // First argument type should always be pipe.
620   if (!Arg0->getType()->isPipeType()) {
621     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
622         << Call->getDirectCallee() << Arg0->getSourceRange();
623     return true;
624   }
625   OpenCLAccessAttr *AccessQual =
626       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
627   // Validates the access qualifier is compatible with the call.
628   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
629   // read_only and write_only, and assumed to be read_only if no qualifier is
630   // specified.
631   switch (Call->getDirectCallee()->getBuiltinID()) {
632   case Builtin::BIread_pipe:
633   case Builtin::BIreserve_read_pipe:
634   case Builtin::BIcommit_read_pipe:
635   case Builtin::BIwork_group_reserve_read_pipe:
636   case Builtin::BIsub_group_reserve_read_pipe:
637   case Builtin::BIwork_group_commit_read_pipe:
638   case Builtin::BIsub_group_commit_read_pipe:
639     if (!(!AccessQual || AccessQual->isReadOnly())) {
640       S.Diag(Arg0->getLocStart(),
641              diag::err_opencl_builtin_pipe_invalid_access_modifier)
642           << "read_only" << Arg0->getSourceRange();
643       return true;
644     }
645     break;
646   case Builtin::BIwrite_pipe:
647   case Builtin::BIreserve_write_pipe:
648   case Builtin::BIcommit_write_pipe:
649   case Builtin::BIwork_group_reserve_write_pipe:
650   case Builtin::BIsub_group_reserve_write_pipe:
651   case Builtin::BIwork_group_commit_write_pipe:
652   case Builtin::BIsub_group_commit_write_pipe:
653     if (!(AccessQual && AccessQual->isWriteOnly())) {
654       S.Diag(Arg0->getLocStart(),
655              diag::err_opencl_builtin_pipe_invalid_access_modifier)
656           << "write_only" << Arg0->getSourceRange();
657       return true;
658     }
659     break;
660   default:
661     break;
662   }
663   return false;
664 }
665 
666 /// Returns true if pipe element type is different from the pointer.
667 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
668   const Expr *Arg0 = Call->getArg(0);
669   const Expr *ArgIdx = Call->getArg(Idx);
670   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
671   const QualType EltTy = PipeTy->getElementType();
672   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
673   // The Idx argument should be a pointer and the type of the pointer and
674   // the type of pipe element should also be the same.
675   if (!ArgTy ||
676       !S.Context.hasSameType(
677           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
678     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
679         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
680         << ArgIdx->getType() << ArgIdx->getSourceRange();
681     return true;
682   }
683   return false;
684 }
685 
686 // \brief Performs semantic analysis for the read/write_pipe call.
687 // \param S Reference to the semantic analyzer.
688 // \param Call A pointer to the builtin call.
689 // \return True if a semantic error has been found, false otherwise.
690 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
691   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
692   // functions have two forms.
693   switch (Call->getNumArgs()) {
694   case 2:
695     if (checkOpenCLPipeArg(S, Call))
696       return true;
697     // The call with 2 arguments should be
698     // read/write_pipe(pipe T, T*).
699     // Check packet type T.
700     if (checkOpenCLPipePacketType(S, Call, 1))
701       return true;
702     break;
703 
704   case 4: {
705     if (checkOpenCLPipeArg(S, Call))
706       return true;
707     // The call with 4 arguments should be
708     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
709     // Check reserve_id_t.
710     if (!Call->getArg(1)->getType()->isReserveIDT()) {
711       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
712           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
713           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
714       return true;
715     }
716 
717     // Check the index.
718     const Expr *Arg2 = Call->getArg(2);
719     if (!Arg2->getType()->isIntegerType() &&
720         !Arg2->getType()->isUnsignedIntegerType()) {
721       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
722           << Call->getDirectCallee() << S.Context.UnsignedIntTy
723           << Arg2->getType() << Arg2->getSourceRange();
724       return true;
725     }
726 
727     // Check packet type T.
728     if (checkOpenCLPipePacketType(S, Call, 3))
729       return true;
730   } break;
731   default:
732     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
733         << Call->getDirectCallee() << Call->getSourceRange();
734     return true;
735   }
736 
737   return false;
738 }
739 
740 // \brief Performs a semantic analysis on the {work_group_/sub_group_
741 //        /_}reserve_{read/write}_pipe
742 // \param S Reference to the semantic analyzer.
743 // \param Call The call to the builtin function to be analyzed.
744 // \return True if a semantic error was found, false otherwise.
745 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
746   if (checkArgCount(S, Call, 2))
747     return true;
748 
749   if (checkOpenCLPipeArg(S, Call))
750     return true;
751 
752   // Check the reserve size.
753   if (!Call->getArg(1)->getType()->isIntegerType() &&
754       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
755     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
756         << Call->getDirectCallee() << S.Context.UnsignedIntTy
757         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
758     return true;
759   }
760 
761   // Since return type of reserve_read/write_pipe built-in function is
762   // reserve_id_t, which is not defined in the builtin def file , we used int
763   // as return type and need to override the return type of these functions.
764   Call->setType(S.Context.OCLReserveIDTy);
765 
766   return false;
767 }
768 
769 // \brief Performs a semantic analysis on {work_group_/sub_group_
770 //        /_}commit_{read/write}_pipe
771 // \param S Reference to the semantic analyzer.
772 // \param Call The call to the builtin function to be analyzed.
773 // \return True if a semantic error was found, false otherwise.
774 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
775   if (checkArgCount(S, Call, 2))
776     return true;
777 
778   if (checkOpenCLPipeArg(S, Call))
779     return true;
780 
781   // Check reserve_id_t.
782   if (!Call->getArg(1)->getType()->isReserveIDT()) {
783     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
784         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
785         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
786     return true;
787   }
788 
789   return false;
790 }
791 
792 // \brief Performs a semantic analysis on the call to built-in Pipe
793 //        Query Functions.
794 // \param S Reference to the semantic analyzer.
795 // \param Call The call to the builtin function to be analyzed.
796 // \return True if a semantic error was found, false otherwise.
797 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
798   if (checkArgCount(S, Call, 1))
799     return true;
800 
801   if (!Call->getArg(0)->getType()->isPipeType()) {
802     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
803         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
804     return true;
805   }
806 
807   return false;
808 }
809 
810 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
811 // \brief Performs semantic analysis for the to_global/local/private call.
812 // \param S Reference to the semantic analyzer.
813 // \param BuiltinID ID of the builtin function.
814 // \param Call A pointer to the builtin call.
815 // \return True if a semantic error has been found, false otherwise.
816 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
817                                     CallExpr *Call) {
818   if (Call->getNumArgs() != 1) {
819     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
820         << Call->getDirectCallee() << Call->getSourceRange();
821     return true;
822   }
823 
824   auto RT = Call->getArg(0)->getType();
825   if (!RT->isPointerType() || RT->getPointeeType()
826       .getAddressSpace() == LangAS::opencl_constant) {
827     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
828         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
829     return true;
830   }
831 
832   RT = RT->getPointeeType();
833   auto Qual = RT.getQualifiers();
834   switch (BuiltinID) {
835   case Builtin::BIto_global:
836     Qual.setAddressSpace(LangAS::opencl_global);
837     break;
838   case Builtin::BIto_local:
839     Qual.setAddressSpace(LangAS::opencl_local);
840     break;
841   case Builtin::BIto_private:
842     Qual.setAddressSpace(LangAS::opencl_private);
843     break;
844   default:
845     llvm_unreachable("Invalid builtin function");
846   }
847   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
848       RT.getUnqualifiedType(), Qual)));
849 
850   return false;
851 }
852 
853 ExprResult
854 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
855                                CallExpr *TheCall) {
856   ExprResult TheCallResult(TheCall);
857 
858   // Find out if any arguments are required to be integer constant expressions.
859   unsigned ICEArguments = 0;
860   ASTContext::GetBuiltinTypeError Error;
861   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
862   if (Error != ASTContext::GE_None)
863     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
864 
865   // If any arguments are required to be ICE's, check and diagnose.
866   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
867     // Skip arguments not required to be ICE's.
868     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
869 
870     llvm::APSInt Result;
871     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
872       return true;
873     ICEArguments &= ~(1 << ArgNo);
874   }
875 
876   switch (BuiltinID) {
877   case Builtin::BI__builtin___CFStringMakeConstantString:
878     assert(TheCall->getNumArgs() == 1 &&
879            "Wrong # arguments to builtin CFStringMakeConstantString");
880     if (CheckObjCString(TheCall->getArg(0)))
881       return ExprError();
882     break;
883   case Builtin::BI__builtin_ms_va_start:
884   case Builtin::BI__builtin_stdarg_start:
885   case Builtin::BI__builtin_va_start:
886     if (SemaBuiltinVAStart(BuiltinID, TheCall))
887       return ExprError();
888     break;
889   case Builtin::BI__va_start: {
890     switch (Context.getTargetInfo().getTriple().getArch()) {
891     case llvm::Triple::arm:
892     case llvm::Triple::thumb:
893       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
894         return ExprError();
895       break;
896     default:
897       if (SemaBuiltinVAStart(BuiltinID, TheCall))
898         return ExprError();
899       break;
900     }
901     break;
902   }
903   case Builtin::BI__builtin_isgreater:
904   case Builtin::BI__builtin_isgreaterequal:
905   case Builtin::BI__builtin_isless:
906   case Builtin::BI__builtin_islessequal:
907   case Builtin::BI__builtin_islessgreater:
908   case Builtin::BI__builtin_isunordered:
909     if (SemaBuiltinUnorderedCompare(TheCall))
910       return ExprError();
911     break;
912   case Builtin::BI__builtin_fpclassify:
913     if (SemaBuiltinFPClassification(TheCall, 6))
914       return ExprError();
915     break;
916   case Builtin::BI__builtin_isfinite:
917   case Builtin::BI__builtin_isinf:
918   case Builtin::BI__builtin_isinf_sign:
919   case Builtin::BI__builtin_isnan:
920   case Builtin::BI__builtin_isnormal:
921     if (SemaBuiltinFPClassification(TheCall, 1))
922       return ExprError();
923     break;
924   case Builtin::BI__builtin_shufflevector:
925     return SemaBuiltinShuffleVector(TheCall);
926     // TheCall will be freed by the smart pointer here, but that's fine, since
927     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
928   case Builtin::BI__builtin_prefetch:
929     if (SemaBuiltinPrefetch(TheCall))
930       return ExprError();
931     break;
932   case Builtin::BI__builtin_alloca_with_align:
933     if (SemaBuiltinAllocaWithAlign(TheCall))
934       return ExprError();
935     break;
936   case Builtin::BI__assume:
937   case Builtin::BI__builtin_assume:
938     if (SemaBuiltinAssume(TheCall))
939       return ExprError();
940     break;
941   case Builtin::BI__builtin_assume_aligned:
942     if (SemaBuiltinAssumeAligned(TheCall))
943       return ExprError();
944     break;
945   case Builtin::BI__builtin_object_size:
946     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
947       return ExprError();
948     break;
949   case Builtin::BI__builtin_longjmp:
950     if (SemaBuiltinLongjmp(TheCall))
951       return ExprError();
952     break;
953   case Builtin::BI__builtin_setjmp:
954     if (SemaBuiltinSetjmp(TheCall))
955       return ExprError();
956     break;
957   case Builtin::BI_setjmp:
958   case Builtin::BI_setjmpex:
959     if (checkArgCount(*this, TheCall, 1))
960       return true;
961     break;
962   case Builtin::BI__builtin_classify_type:
963     if (checkArgCount(*this, TheCall, 1)) return true;
964     TheCall->setType(Context.IntTy);
965     break;
966   case Builtin::BI__builtin_constant_p:
967     if (checkArgCount(*this, TheCall, 1)) return true;
968     TheCall->setType(Context.IntTy);
969     break;
970   case Builtin::BI__sync_fetch_and_add:
971   case Builtin::BI__sync_fetch_and_add_1:
972   case Builtin::BI__sync_fetch_and_add_2:
973   case Builtin::BI__sync_fetch_and_add_4:
974   case Builtin::BI__sync_fetch_and_add_8:
975   case Builtin::BI__sync_fetch_and_add_16:
976   case Builtin::BI__sync_fetch_and_sub:
977   case Builtin::BI__sync_fetch_and_sub_1:
978   case Builtin::BI__sync_fetch_and_sub_2:
979   case Builtin::BI__sync_fetch_and_sub_4:
980   case Builtin::BI__sync_fetch_and_sub_8:
981   case Builtin::BI__sync_fetch_and_sub_16:
982   case Builtin::BI__sync_fetch_and_or:
983   case Builtin::BI__sync_fetch_and_or_1:
984   case Builtin::BI__sync_fetch_and_or_2:
985   case Builtin::BI__sync_fetch_and_or_4:
986   case Builtin::BI__sync_fetch_and_or_8:
987   case Builtin::BI__sync_fetch_and_or_16:
988   case Builtin::BI__sync_fetch_and_and:
989   case Builtin::BI__sync_fetch_and_and_1:
990   case Builtin::BI__sync_fetch_and_and_2:
991   case Builtin::BI__sync_fetch_and_and_4:
992   case Builtin::BI__sync_fetch_and_and_8:
993   case Builtin::BI__sync_fetch_and_and_16:
994   case Builtin::BI__sync_fetch_and_xor:
995   case Builtin::BI__sync_fetch_and_xor_1:
996   case Builtin::BI__sync_fetch_and_xor_2:
997   case Builtin::BI__sync_fetch_and_xor_4:
998   case Builtin::BI__sync_fetch_and_xor_8:
999   case Builtin::BI__sync_fetch_and_xor_16:
1000   case Builtin::BI__sync_fetch_and_nand:
1001   case Builtin::BI__sync_fetch_and_nand_1:
1002   case Builtin::BI__sync_fetch_and_nand_2:
1003   case Builtin::BI__sync_fetch_and_nand_4:
1004   case Builtin::BI__sync_fetch_and_nand_8:
1005   case Builtin::BI__sync_fetch_and_nand_16:
1006   case Builtin::BI__sync_add_and_fetch:
1007   case Builtin::BI__sync_add_and_fetch_1:
1008   case Builtin::BI__sync_add_and_fetch_2:
1009   case Builtin::BI__sync_add_and_fetch_4:
1010   case Builtin::BI__sync_add_and_fetch_8:
1011   case Builtin::BI__sync_add_and_fetch_16:
1012   case Builtin::BI__sync_sub_and_fetch:
1013   case Builtin::BI__sync_sub_and_fetch_1:
1014   case Builtin::BI__sync_sub_and_fetch_2:
1015   case Builtin::BI__sync_sub_and_fetch_4:
1016   case Builtin::BI__sync_sub_and_fetch_8:
1017   case Builtin::BI__sync_sub_and_fetch_16:
1018   case Builtin::BI__sync_and_and_fetch:
1019   case Builtin::BI__sync_and_and_fetch_1:
1020   case Builtin::BI__sync_and_and_fetch_2:
1021   case Builtin::BI__sync_and_and_fetch_4:
1022   case Builtin::BI__sync_and_and_fetch_8:
1023   case Builtin::BI__sync_and_and_fetch_16:
1024   case Builtin::BI__sync_or_and_fetch:
1025   case Builtin::BI__sync_or_and_fetch_1:
1026   case Builtin::BI__sync_or_and_fetch_2:
1027   case Builtin::BI__sync_or_and_fetch_4:
1028   case Builtin::BI__sync_or_and_fetch_8:
1029   case Builtin::BI__sync_or_and_fetch_16:
1030   case Builtin::BI__sync_xor_and_fetch:
1031   case Builtin::BI__sync_xor_and_fetch_1:
1032   case Builtin::BI__sync_xor_and_fetch_2:
1033   case Builtin::BI__sync_xor_and_fetch_4:
1034   case Builtin::BI__sync_xor_and_fetch_8:
1035   case Builtin::BI__sync_xor_and_fetch_16:
1036   case Builtin::BI__sync_nand_and_fetch:
1037   case Builtin::BI__sync_nand_and_fetch_1:
1038   case Builtin::BI__sync_nand_and_fetch_2:
1039   case Builtin::BI__sync_nand_and_fetch_4:
1040   case Builtin::BI__sync_nand_and_fetch_8:
1041   case Builtin::BI__sync_nand_and_fetch_16:
1042   case Builtin::BI__sync_val_compare_and_swap:
1043   case Builtin::BI__sync_val_compare_and_swap_1:
1044   case Builtin::BI__sync_val_compare_and_swap_2:
1045   case Builtin::BI__sync_val_compare_and_swap_4:
1046   case Builtin::BI__sync_val_compare_and_swap_8:
1047   case Builtin::BI__sync_val_compare_and_swap_16:
1048   case Builtin::BI__sync_bool_compare_and_swap:
1049   case Builtin::BI__sync_bool_compare_and_swap_1:
1050   case Builtin::BI__sync_bool_compare_and_swap_2:
1051   case Builtin::BI__sync_bool_compare_and_swap_4:
1052   case Builtin::BI__sync_bool_compare_and_swap_8:
1053   case Builtin::BI__sync_bool_compare_and_swap_16:
1054   case Builtin::BI__sync_lock_test_and_set:
1055   case Builtin::BI__sync_lock_test_and_set_1:
1056   case Builtin::BI__sync_lock_test_and_set_2:
1057   case Builtin::BI__sync_lock_test_and_set_4:
1058   case Builtin::BI__sync_lock_test_and_set_8:
1059   case Builtin::BI__sync_lock_test_and_set_16:
1060   case Builtin::BI__sync_lock_release:
1061   case Builtin::BI__sync_lock_release_1:
1062   case Builtin::BI__sync_lock_release_2:
1063   case Builtin::BI__sync_lock_release_4:
1064   case Builtin::BI__sync_lock_release_8:
1065   case Builtin::BI__sync_lock_release_16:
1066   case Builtin::BI__sync_swap:
1067   case Builtin::BI__sync_swap_1:
1068   case Builtin::BI__sync_swap_2:
1069   case Builtin::BI__sync_swap_4:
1070   case Builtin::BI__sync_swap_8:
1071   case Builtin::BI__sync_swap_16:
1072     return SemaBuiltinAtomicOverloaded(TheCallResult);
1073   case Builtin::BI__builtin_nontemporal_load:
1074   case Builtin::BI__builtin_nontemporal_store:
1075     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1076 #define BUILTIN(ID, TYPE, ATTRS)
1077 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1078   case Builtin::BI##ID: \
1079     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1080 #include "clang/Basic/Builtins.def"
1081   case Builtin::BI__annotation:
1082     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1083       return ExprError();
1084     break;
1085   case Builtin::BI__builtin_annotation:
1086     if (SemaBuiltinAnnotation(*this, TheCall))
1087       return ExprError();
1088     break;
1089   case Builtin::BI__builtin_addressof:
1090     if (SemaBuiltinAddressof(*this, TheCall))
1091       return ExprError();
1092     break;
1093   case Builtin::BI__builtin_add_overflow:
1094   case Builtin::BI__builtin_sub_overflow:
1095   case Builtin::BI__builtin_mul_overflow:
1096     if (SemaBuiltinOverflow(*this, TheCall))
1097       return ExprError();
1098     break;
1099   case Builtin::BI__builtin_operator_new:
1100   case Builtin::BI__builtin_operator_delete: {
1101     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1102     ExprResult Res =
1103         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1104     if (Res.isInvalid())
1105       CorrectDelayedTyposInExpr(TheCallResult.get());
1106     return Res;
1107   }
1108   // check secure string manipulation functions where overflows
1109   // are detectable at compile time
1110   case Builtin::BI__builtin___memcpy_chk:
1111   case Builtin::BI__builtin___memmove_chk:
1112   case Builtin::BI__builtin___memset_chk:
1113   case Builtin::BI__builtin___strlcat_chk:
1114   case Builtin::BI__builtin___strlcpy_chk:
1115   case Builtin::BI__builtin___strncat_chk:
1116   case Builtin::BI__builtin___strncpy_chk:
1117   case Builtin::BI__builtin___stpncpy_chk:
1118     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1119     break;
1120   case Builtin::BI__builtin___memccpy_chk:
1121     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1122     break;
1123   case Builtin::BI__builtin___snprintf_chk:
1124   case Builtin::BI__builtin___vsnprintf_chk:
1125     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1126     break;
1127   case Builtin::BI__builtin_call_with_static_chain:
1128     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1129       return ExprError();
1130     break;
1131   case Builtin::BI__exception_code:
1132   case Builtin::BI_exception_code:
1133     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1134                                  diag::err_seh___except_block))
1135       return ExprError();
1136     break;
1137   case Builtin::BI__exception_info:
1138   case Builtin::BI_exception_info:
1139     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1140                                  diag::err_seh___except_filter))
1141       return ExprError();
1142     break;
1143   case Builtin::BI__GetExceptionInfo:
1144     if (checkArgCount(*this, TheCall, 1))
1145       return ExprError();
1146 
1147     if (CheckCXXThrowOperand(
1148             TheCall->getLocStart(),
1149             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1150             TheCall))
1151       return ExprError();
1152 
1153     TheCall->setType(Context.VoidPtrTy);
1154     break;
1155   // OpenCL v2.0, s6.13.16 - Pipe functions
1156   case Builtin::BIread_pipe:
1157   case Builtin::BIwrite_pipe:
1158     // Since those two functions are declared with var args, we need a semantic
1159     // check for the argument.
1160     if (SemaBuiltinRWPipe(*this, TheCall))
1161       return ExprError();
1162     TheCall->setType(Context.IntTy);
1163     break;
1164   case Builtin::BIreserve_read_pipe:
1165   case Builtin::BIreserve_write_pipe:
1166   case Builtin::BIwork_group_reserve_read_pipe:
1167   case Builtin::BIwork_group_reserve_write_pipe:
1168     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1169       return ExprError();
1170     break;
1171   case Builtin::BIsub_group_reserve_read_pipe:
1172   case Builtin::BIsub_group_reserve_write_pipe:
1173     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1174         SemaBuiltinReserveRWPipe(*this, TheCall))
1175       return ExprError();
1176     break;
1177   case Builtin::BIcommit_read_pipe:
1178   case Builtin::BIcommit_write_pipe:
1179   case Builtin::BIwork_group_commit_read_pipe:
1180   case Builtin::BIwork_group_commit_write_pipe:
1181     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1182       return ExprError();
1183     break;
1184   case Builtin::BIsub_group_commit_read_pipe:
1185   case Builtin::BIsub_group_commit_write_pipe:
1186     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1187         SemaBuiltinCommitRWPipe(*this, TheCall))
1188       return ExprError();
1189     break;
1190   case Builtin::BIget_pipe_num_packets:
1191   case Builtin::BIget_pipe_max_packets:
1192     if (SemaBuiltinPipePackets(*this, TheCall))
1193       return ExprError();
1194     TheCall->setType(Context.UnsignedIntTy);
1195     break;
1196   case Builtin::BIto_global:
1197   case Builtin::BIto_local:
1198   case Builtin::BIto_private:
1199     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1200       return ExprError();
1201     break;
1202   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1203   case Builtin::BIenqueue_kernel:
1204     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1205       return ExprError();
1206     break;
1207   case Builtin::BIget_kernel_work_group_size:
1208   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1209     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1210       return ExprError();
1211     break;
1212   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1213   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1214     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1215       return ExprError();
1216     break;
1217   case Builtin::BI__builtin_os_log_format:
1218   case Builtin::BI__builtin_os_log_format_buffer_size:
1219     if (SemaBuiltinOSLogFormat(TheCall))
1220       return ExprError();
1221     break;
1222   }
1223 
1224   // Since the target specific builtins for each arch overlap, only check those
1225   // of the arch we are compiling for.
1226   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1227     switch (Context.getTargetInfo().getTriple().getArch()) {
1228       case llvm::Triple::arm:
1229       case llvm::Triple::armeb:
1230       case llvm::Triple::thumb:
1231       case llvm::Triple::thumbeb:
1232         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1233           return ExprError();
1234         break;
1235       case llvm::Triple::aarch64:
1236       case llvm::Triple::aarch64_be:
1237         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1238           return ExprError();
1239         break;
1240       case llvm::Triple::mips:
1241       case llvm::Triple::mipsel:
1242       case llvm::Triple::mips64:
1243       case llvm::Triple::mips64el:
1244         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1245           return ExprError();
1246         break;
1247       case llvm::Triple::systemz:
1248         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1249           return ExprError();
1250         break;
1251       case llvm::Triple::x86:
1252       case llvm::Triple::x86_64:
1253         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1254           return ExprError();
1255         break;
1256       case llvm::Triple::ppc:
1257       case llvm::Triple::ppc64:
1258       case llvm::Triple::ppc64le:
1259         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1260           return ExprError();
1261         break;
1262       default:
1263         break;
1264     }
1265   }
1266 
1267   return TheCallResult;
1268 }
1269 
1270 // Get the valid immediate range for the specified NEON type code.
1271 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1272   NeonTypeFlags Type(t);
1273   int IsQuad = ForceQuad ? true : Type.isQuad();
1274   switch (Type.getEltType()) {
1275   case NeonTypeFlags::Int8:
1276   case NeonTypeFlags::Poly8:
1277     return shift ? 7 : (8 << IsQuad) - 1;
1278   case NeonTypeFlags::Int16:
1279   case NeonTypeFlags::Poly16:
1280     return shift ? 15 : (4 << IsQuad) - 1;
1281   case NeonTypeFlags::Int32:
1282     return shift ? 31 : (2 << IsQuad) - 1;
1283   case NeonTypeFlags::Int64:
1284   case NeonTypeFlags::Poly64:
1285     return shift ? 63 : (1 << IsQuad) - 1;
1286   case NeonTypeFlags::Poly128:
1287     return shift ? 127 : (1 << IsQuad) - 1;
1288   case NeonTypeFlags::Float16:
1289     assert(!shift && "cannot shift float types!");
1290     return (4 << IsQuad) - 1;
1291   case NeonTypeFlags::Float32:
1292     assert(!shift && "cannot shift float types!");
1293     return (2 << IsQuad) - 1;
1294   case NeonTypeFlags::Float64:
1295     assert(!shift && "cannot shift float types!");
1296     return (1 << IsQuad) - 1;
1297   }
1298   llvm_unreachable("Invalid NeonTypeFlag!");
1299 }
1300 
1301 /// getNeonEltType - Return the QualType corresponding to the elements of
1302 /// the vector type specified by the NeonTypeFlags.  This is used to check
1303 /// the pointer arguments for Neon load/store intrinsics.
1304 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1305                                bool IsPolyUnsigned, bool IsInt64Long) {
1306   switch (Flags.getEltType()) {
1307   case NeonTypeFlags::Int8:
1308     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1309   case NeonTypeFlags::Int16:
1310     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1311   case NeonTypeFlags::Int32:
1312     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1313   case NeonTypeFlags::Int64:
1314     if (IsInt64Long)
1315       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1316     else
1317       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1318                                 : Context.LongLongTy;
1319   case NeonTypeFlags::Poly8:
1320     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1321   case NeonTypeFlags::Poly16:
1322     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1323   case NeonTypeFlags::Poly64:
1324     if (IsInt64Long)
1325       return Context.UnsignedLongTy;
1326     else
1327       return Context.UnsignedLongLongTy;
1328   case NeonTypeFlags::Poly128:
1329     break;
1330   case NeonTypeFlags::Float16:
1331     return Context.HalfTy;
1332   case NeonTypeFlags::Float32:
1333     return Context.FloatTy;
1334   case NeonTypeFlags::Float64:
1335     return Context.DoubleTy;
1336   }
1337   llvm_unreachable("Invalid NeonTypeFlag!");
1338 }
1339 
1340 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1341   llvm::APSInt Result;
1342   uint64_t mask = 0;
1343   unsigned TV = 0;
1344   int PtrArgNum = -1;
1345   bool HasConstPtr = false;
1346   switch (BuiltinID) {
1347 #define GET_NEON_OVERLOAD_CHECK
1348 #include "clang/Basic/arm_neon.inc"
1349 #include "clang/Basic/arm_fp16.inc"
1350 #undef GET_NEON_OVERLOAD_CHECK
1351   }
1352 
1353   // For NEON intrinsics which are overloaded on vector element type, validate
1354   // the immediate which specifies which variant to emit.
1355   unsigned ImmArg = TheCall->getNumArgs()-1;
1356   if (mask) {
1357     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1358       return true;
1359 
1360     TV = Result.getLimitedValue(64);
1361     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1362       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1363         << TheCall->getArg(ImmArg)->getSourceRange();
1364   }
1365 
1366   if (PtrArgNum >= 0) {
1367     // Check that pointer arguments have the specified type.
1368     Expr *Arg = TheCall->getArg(PtrArgNum);
1369     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1370       Arg = ICE->getSubExpr();
1371     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1372     QualType RHSTy = RHS.get()->getType();
1373 
1374     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1375     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1376                           Arch == llvm::Triple::aarch64_be;
1377     bool IsInt64Long =
1378         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1379     QualType EltTy =
1380         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1381     if (HasConstPtr)
1382       EltTy = EltTy.withConst();
1383     QualType LHSTy = Context.getPointerType(EltTy);
1384     AssignConvertType ConvTy;
1385     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1386     if (RHS.isInvalid())
1387       return true;
1388     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1389                                  RHS.get(), AA_Assigning))
1390       return true;
1391   }
1392 
1393   // For NEON intrinsics which take an immediate value as part of the
1394   // instruction, range check them here.
1395   unsigned i = 0, l = 0, u = 0;
1396   switch (BuiltinID) {
1397   default:
1398     return false;
1399 #define GET_NEON_IMMEDIATE_CHECK
1400 #include "clang/Basic/arm_neon.inc"
1401 #include "clang/Basic/arm_fp16.inc"
1402 #undef GET_NEON_IMMEDIATE_CHECK
1403   }
1404 
1405   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1406 }
1407 
1408 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1409                                         unsigned MaxWidth) {
1410   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1411           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1412           BuiltinID == ARM::BI__builtin_arm_strex ||
1413           BuiltinID == ARM::BI__builtin_arm_stlex ||
1414           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1415           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1416           BuiltinID == AArch64::BI__builtin_arm_strex ||
1417           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1418          "unexpected ARM builtin");
1419   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1420                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1421                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1422                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1423 
1424   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1425 
1426   // Ensure that we have the proper number of arguments.
1427   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1428     return true;
1429 
1430   // Inspect the pointer argument of the atomic builtin.  This should always be
1431   // a pointer type, whose element is an integral scalar or pointer type.
1432   // Because it is a pointer type, we don't have to worry about any implicit
1433   // casts here.
1434   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1435   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1436   if (PointerArgRes.isInvalid())
1437     return true;
1438   PointerArg = PointerArgRes.get();
1439 
1440   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1441   if (!pointerType) {
1442     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1443       << PointerArg->getType() << PointerArg->getSourceRange();
1444     return true;
1445   }
1446 
1447   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1448   // task is to insert the appropriate casts into the AST. First work out just
1449   // what the appropriate type is.
1450   QualType ValType = pointerType->getPointeeType();
1451   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1452   if (IsLdrex)
1453     AddrType.addConst();
1454 
1455   // Issue a warning if the cast is dodgy.
1456   CastKind CastNeeded = CK_NoOp;
1457   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1458     CastNeeded = CK_BitCast;
1459     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1460       << PointerArg->getType()
1461       << Context.getPointerType(AddrType)
1462       << AA_Passing << PointerArg->getSourceRange();
1463   }
1464 
1465   // Finally, do the cast and replace the argument with the corrected version.
1466   AddrType = Context.getPointerType(AddrType);
1467   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1468   if (PointerArgRes.isInvalid())
1469     return true;
1470   PointerArg = PointerArgRes.get();
1471 
1472   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1473 
1474   // In general, we allow ints, floats and pointers to be loaded and stored.
1475   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1476       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1477     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1478       << PointerArg->getType() << PointerArg->getSourceRange();
1479     return true;
1480   }
1481 
1482   // But ARM doesn't have instructions to deal with 128-bit versions.
1483   if (Context.getTypeSize(ValType) > MaxWidth) {
1484     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1485     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1486       << PointerArg->getType() << PointerArg->getSourceRange();
1487     return true;
1488   }
1489 
1490   switch (ValType.getObjCLifetime()) {
1491   case Qualifiers::OCL_None:
1492   case Qualifiers::OCL_ExplicitNone:
1493     // okay
1494     break;
1495 
1496   case Qualifiers::OCL_Weak:
1497   case Qualifiers::OCL_Strong:
1498   case Qualifiers::OCL_Autoreleasing:
1499     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1500       << ValType << PointerArg->getSourceRange();
1501     return true;
1502   }
1503 
1504   if (IsLdrex) {
1505     TheCall->setType(ValType);
1506     return false;
1507   }
1508 
1509   // Initialize the argument to be stored.
1510   ExprResult ValArg = TheCall->getArg(0);
1511   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1512       Context, ValType, /*consume*/ false);
1513   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1514   if (ValArg.isInvalid())
1515     return true;
1516   TheCall->setArg(0, ValArg.get());
1517 
1518   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1519   // but the custom checker bypasses all default analysis.
1520   TheCall->setType(Context.IntTy);
1521   return false;
1522 }
1523 
1524 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1525   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1526       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1527       BuiltinID == ARM::BI__builtin_arm_strex ||
1528       BuiltinID == ARM::BI__builtin_arm_stlex) {
1529     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1530   }
1531 
1532   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1533     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1534       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1535   }
1536 
1537   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1538       BuiltinID == ARM::BI__builtin_arm_wsr64)
1539     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1540 
1541   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1542       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1543       BuiltinID == ARM::BI__builtin_arm_wsr ||
1544       BuiltinID == ARM::BI__builtin_arm_wsrp)
1545     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1546 
1547   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1548     return true;
1549 
1550   // For intrinsics which take an immediate value as part of the instruction,
1551   // range check them here.
1552   // FIXME: VFP Intrinsics should error if VFP not present.
1553   switch (BuiltinID) {
1554   default: return false;
1555   case ARM::BI__builtin_arm_ssat:
1556     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1557   case ARM::BI__builtin_arm_usat:
1558     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1559   case ARM::BI__builtin_arm_ssat16:
1560     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1561   case ARM::BI__builtin_arm_usat16:
1562     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1563   case ARM::BI__builtin_arm_vcvtr_f:
1564   case ARM::BI__builtin_arm_vcvtr_d:
1565     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1566   case ARM::BI__builtin_arm_dmb:
1567   case ARM::BI__builtin_arm_dsb:
1568   case ARM::BI__builtin_arm_isb:
1569   case ARM::BI__builtin_arm_dbg:
1570     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1571   }
1572 }
1573 
1574 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1575                                          CallExpr *TheCall) {
1576   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1577       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1578       BuiltinID == AArch64::BI__builtin_arm_strex ||
1579       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1580     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1581   }
1582 
1583   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1584     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1585       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1586       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1587       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1588   }
1589 
1590   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1591       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1592     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1593 
1594   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1595       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1596       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1597       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1598     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1599 
1600   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1601     return true;
1602 
1603   // For intrinsics which take an immediate value as part of the instruction,
1604   // range check them here.
1605   unsigned i = 0, l = 0, u = 0;
1606   switch (BuiltinID) {
1607   default: return false;
1608   case AArch64::BI__builtin_arm_dmb:
1609   case AArch64::BI__builtin_arm_dsb:
1610   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1611   }
1612 
1613   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1614 }
1615 
1616 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1617 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1618 // ordering for DSP is unspecified. MSA is ordered by the data format used
1619 // by the underlying instruction i.e., df/m, df/n and then by size.
1620 //
1621 // FIXME: The size tests here should instead be tablegen'd along with the
1622 //        definitions from include/clang/Basic/BuiltinsMips.def.
1623 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1624 //        be too.
1625 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1626   unsigned i = 0, l = 0, u = 0, m = 0;
1627   switch (BuiltinID) {
1628   default: return false;
1629   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1630   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1631   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1632   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1633   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1634   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1635   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1636   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1637   // df/m field.
1638   // These intrinsics take an unsigned 3 bit immediate.
1639   case Mips::BI__builtin_msa_bclri_b:
1640   case Mips::BI__builtin_msa_bnegi_b:
1641   case Mips::BI__builtin_msa_bseti_b:
1642   case Mips::BI__builtin_msa_sat_s_b:
1643   case Mips::BI__builtin_msa_sat_u_b:
1644   case Mips::BI__builtin_msa_slli_b:
1645   case Mips::BI__builtin_msa_srai_b:
1646   case Mips::BI__builtin_msa_srari_b:
1647   case Mips::BI__builtin_msa_srli_b:
1648   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1649   case Mips::BI__builtin_msa_binsli_b:
1650   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1651   // These intrinsics take an unsigned 4 bit immediate.
1652   case Mips::BI__builtin_msa_bclri_h:
1653   case Mips::BI__builtin_msa_bnegi_h:
1654   case Mips::BI__builtin_msa_bseti_h:
1655   case Mips::BI__builtin_msa_sat_s_h:
1656   case Mips::BI__builtin_msa_sat_u_h:
1657   case Mips::BI__builtin_msa_slli_h:
1658   case Mips::BI__builtin_msa_srai_h:
1659   case Mips::BI__builtin_msa_srari_h:
1660   case Mips::BI__builtin_msa_srli_h:
1661   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1662   case Mips::BI__builtin_msa_binsli_h:
1663   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1664   // These intrinsics take an unsigned 5 bit immedate.
1665   // The first block of intrinsics actually have an unsigned 5 bit field,
1666   // not a df/n field.
1667   case Mips::BI__builtin_msa_clei_u_b:
1668   case Mips::BI__builtin_msa_clei_u_h:
1669   case Mips::BI__builtin_msa_clei_u_w:
1670   case Mips::BI__builtin_msa_clei_u_d:
1671   case Mips::BI__builtin_msa_clti_u_b:
1672   case Mips::BI__builtin_msa_clti_u_h:
1673   case Mips::BI__builtin_msa_clti_u_w:
1674   case Mips::BI__builtin_msa_clti_u_d:
1675   case Mips::BI__builtin_msa_maxi_u_b:
1676   case Mips::BI__builtin_msa_maxi_u_h:
1677   case Mips::BI__builtin_msa_maxi_u_w:
1678   case Mips::BI__builtin_msa_maxi_u_d:
1679   case Mips::BI__builtin_msa_mini_u_b:
1680   case Mips::BI__builtin_msa_mini_u_h:
1681   case Mips::BI__builtin_msa_mini_u_w:
1682   case Mips::BI__builtin_msa_mini_u_d:
1683   case Mips::BI__builtin_msa_addvi_b:
1684   case Mips::BI__builtin_msa_addvi_h:
1685   case Mips::BI__builtin_msa_addvi_w:
1686   case Mips::BI__builtin_msa_addvi_d:
1687   case Mips::BI__builtin_msa_bclri_w:
1688   case Mips::BI__builtin_msa_bnegi_w:
1689   case Mips::BI__builtin_msa_bseti_w:
1690   case Mips::BI__builtin_msa_sat_s_w:
1691   case Mips::BI__builtin_msa_sat_u_w:
1692   case Mips::BI__builtin_msa_slli_w:
1693   case Mips::BI__builtin_msa_srai_w:
1694   case Mips::BI__builtin_msa_srari_w:
1695   case Mips::BI__builtin_msa_srli_w:
1696   case Mips::BI__builtin_msa_srlri_w:
1697   case Mips::BI__builtin_msa_subvi_b:
1698   case Mips::BI__builtin_msa_subvi_h:
1699   case Mips::BI__builtin_msa_subvi_w:
1700   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1701   case Mips::BI__builtin_msa_binsli_w:
1702   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1703   // These intrinsics take an unsigned 6 bit immediate.
1704   case Mips::BI__builtin_msa_bclri_d:
1705   case Mips::BI__builtin_msa_bnegi_d:
1706   case Mips::BI__builtin_msa_bseti_d:
1707   case Mips::BI__builtin_msa_sat_s_d:
1708   case Mips::BI__builtin_msa_sat_u_d:
1709   case Mips::BI__builtin_msa_slli_d:
1710   case Mips::BI__builtin_msa_srai_d:
1711   case Mips::BI__builtin_msa_srari_d:
1712   case Mips::BI__builtin_msa_srli_d:
1713   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1714   case Mips::BI__builtin_msa_binsli_d:
1715   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1716   // These intrinsics take a signed 5 bit immediate.
1717   case Mips::BI__builtin_msa_ceqi_b:
1718   case Mips::BI__builtin_msa_ceqi_h:
1719   case Mips::BI__builtin_msa_ceqi_w:
1720   case Mips::BI__builtin_msa_ceqi_d:
1721   case Mips::BI__builtin_msa_clti_s_b:
1722   case Mips::BI__builtin_msa_clti_s_h:
1723   case Mips::BI__builtin_msa_clti_s_w:
1724   case Mips::BI__builtin_msa_clti_s_d:
1725   case Mips::BI__builtin_msa_clei_s_b:
1726   case Mips::BI__builtin_msa_clei_s_h:
1727   case Mips::BI__builtin_msa_clei_s_w:
1728   case Mips::BI__builtin_msa_clei_s_d:
1729   case Mips::BI__builtin_msa_maxi_s_b:
1730   case Mips::BI__builtin_msa_maxi_s_h:
1731   case Mips::BI__builtin_msa_maxi_s_w:
1732   case Mips::BI__builtin_msa_maxi_s_d:
1733   case Mips::BI__builtin_msa_mini_s_b:
1734   case Mips::BI__builtin_msa_mini_s_h:
1735   case Mips::BI__builtin_msa_mini_s_w:
1736   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1737   // These intrinsics take an unsigned 8 bit immediate.
1738   case Mips::BI__builtin_msa_andi_b:
1739   case Mips::BI__builtin_msa_nori_b:
1740   case Mips::BI__builtin_msa_ori_b:
1741   case Mips::BI__builtin_msa_shf_b:
1742   case Mips::BI__builtin_msa_shf_h:
1743   case Mips::BI__builtin_msa_shf_w:
1744   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1745   case Mips::BI__builtin_msa_bseli_b:
1746   case Mips::BI__builtin_msa_bmnzi_b:
1747   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1748   // df/n format
1749   // These intrinsics take an unsigned 4 bit immediate.
1750   case Mips::BI__builtin_msa_copy_s_b:
1751   case Mips::BI__builtin_msa_copy_u_b:
1752   case Mips::BI__builtin_msa_insve_b:
1753   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1754   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1755   // These intrinsics take an unsigned 3 bit immediate.
1756   case Mips::BI__builtin_msa_copy_s_h:
1757   case Mips::BI__builtin_msa_copy_u_h:
1758   case Mips::BI__builtin_msa_insve_h:
1759   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1760   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1761   // These intrinsics take an unsigned 2 bit immediate.
1762   case Mips::BI__builtin_msa_copy_s_w:
1763   case Mips::BI__builtin_msa_copy_u_w:
1764   case Mips::BI__builtin_msa_insve_w:
1765   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1766   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1767   // These intrinsics take an unsigned 1 bit immediate.
1768   case Mips::BI__builtin_msa_copy_s_d:
1769   case Mips::BI__builtin_msa_copy_u_d:
1770   case Mips::BI__builtin_msa_insve_d:
1771   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1772   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1773   // Memory offsets and immediate loads.
1774   // These intrinsics take a signed 10 bit immediate.
1775   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1776   case Mips::BI__builtin_msa_ldi_h:
1777   case Mips::BI__builtin_msa_ldi_w:
1778   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1779   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1780   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1781   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1782   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1783   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1784   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1785   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1786   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1787   }
1788 
1789   if (!m)
1790     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1791 
1792   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1793          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1794 }
1795 
1796 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1797   unsigned i = 0, l = 0, u = 0;
1798   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1799                       BuiltinID == PPC::BI__builtin_divdeu ||
1800                       BuiltinID == PPC::BI__builtin_bpermd;
1801   bool IsTarget64Bit = Context.getTargetInfo()
1802                               .getTypeWidth(Context
1803                                             .getTargetInfo()
1804                                             .getIntPtrType()) == 64;
1805   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1806                        BuiltinID == PPC::BI__builtin_divweu ||
1807                        BuiltinID == PPC::BI__builtin_divde ||
1808                        BuiltinID == PPC::BI__builtin_divdeu;
1809 
1810   if (Is64BitBltin && !IsTarget64Bit)
1811       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1812              << TheCall->getSourceRange();
1813 
1814   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1815       (BuiltinID == PPC::BI__builtin_bpermd &&
1816        !Context.getTargetInfo().hasFeature("bpermd")))
1817     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1818            << TheCall->getSourceRange();
1819 
1820   switch (BuiltinID) {
1821   default: return false;
1822   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1823   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1824     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1825            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1826   case PPC::BI__builtin_tbegin:
1827   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1828   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1829   case PPC::BI__builtin_tabortwc:
1830   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1831   case PPC::BI__builtin_tabortwci:
1832   case PPC::BI__builtin_tabortdci:
1833     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1834            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1835   case PPC::BI__builtin_vsx_xxpermdi:
1836   case PPC::BI__builtin_vsx_xxsldwi:
1837     return SemaBuiltinVSX(TheCall);
1838   }
1839   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1840 }
1841 
1842 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1843                                            CallExpr *TheCall) {
1844   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1845     Expr *Arg = TheCall->getArg(0);
1846     llvm::APSInt AbortCode(32);
1847     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1848         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1849       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1850              << Arg->getSourceRange();
1851   }
1852 
1853   // For intrinsics which take an immediate value as part of the instruction,
1854   // range check them here.
1855   unsigned i = 0, l = 0, u = 0;
1856   switch (BuiltinID) {
1857   default: return false;
1858   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1859   case SystemZ::BI__builtin_s390_verimb:
1860   case SystemZ::BI__builtin_s390_verimh:
1861   case SystemZ::BI__builtin_s390_verimf:
1862   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1863   case SystemZ::BI__builtin_s390_vfaeb:
1864   case SystemZ::BI__builtin_s390_vfaeh:
1865   case SystemZ::BI__builtin_s390_vfaef:
1866   case SystemZ::BI__builtin_s390_vfaebs:
1867   case SystemZ::BI__builtin_s390_vfaehs:
1868   case SystemZ::BI__builtin_s390_vfaefs:
1869   case SystemZ::BI__builtin_s390_vfaezb:
1870   case SystemZ::BI__builtin_s390_vfaezh:
1871   case SystemZ::BI__builtin_s390_vfaezf:
1872   case SystemZ::BI__builtin_s390_vfaezbs:
1873   case SystemZ::BI__builtin_s390_vfaezhs:
1874   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1875   case SystemZ::BI__builtin_s390_vfisb:
1876   case SystemZ::BI__builtin_s390_vfidb:
1877     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1878            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1879   case SystemZ::BI__builtin_s390_vftcisb:
1880   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1881   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1882   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1883   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1884   case SystemZ::BI__builtin_s390_vstrcb:
1885   case SystemZ::BI__builtin_s390_vstrch:
1886   case SystemZ::BI__builtin_s390_vstrcf:
1887   case SystemZ::BI__builtin_s390_vstrczb:
1888   case SystemZ::BI__builtin_s390_vstrczh:
1889   case SystemZ::BI__builtin_s390_vstrczf:
1890   case SystemZ::BI__builtin_s390_vstrcbs:
1891   case SystemZ::BI__builtin_s390_vstrchs:
1892   case SystemZ::BI__builtin_s390_vstrcfs:
1893   case SystemZ::BI__builtin_s390_vstrczbs:
1894   case SystemZ::BI__builtin_s390_vstrczhs:
1895   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1896   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1897   case SystemZ::BI__builtin_s390_vfminsb:
1898   case SystemZ::BI__builtin_s390_vfmaxsb:
1899   case SystemZ::BI__builtin_s390_vfmindb:
1900   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
1901   }
1902   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1903 }
1904 
1905 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1906 /// This checks that the target supports __builtin_cpu_supports and
1907 /// that the string argument is constant and valid.
1908 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1909   Expr *Arg = TheCall->getArg(0);
1910 
1911   // Check if the argument is a string literal.
1912   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1913     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1914            << Arg->getSourceRange();
1915 
1916   // Check the contents of the string.
1917   StringRef Feature =
1918       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1919   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1920     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1921            << Arg->getSourceRange();
1922   return false;
1923 }
1924 
1925 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1926 /// This checks that the target supports __builtin_cpu_is and
1927 /// that the string argument is constant and valid.
1928 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1929   Expr *Arg = TheCall->getArg(0);
1930 
1931   // Check if the argument is a string literal.
1932   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1933     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1934            << Arg->getSourceRange();
1935 
1936   // Check the contents of the string.
1937   StringRef Feature =
1938       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1939   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1940     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1941            << Arg->getSourceRange();
1942   return false;
1943 }
1944 
1945 // Check if the rounding mode is legal.
1946 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1947   // Indicates if this instruction has rounding control or just SAE.
1948   bool HasRC = false;
1949 
1950   unsigned ArgNum = 0;
1951   switch (BuiltinID) {
1952   default:
1953     return false;
1954   case X86::BI__builtin_ia32_vcvttsd2si32:
1955   case X86::BI__builtin_ia32_vcvttsd2si64:
1956   case X86::BI__builtin_ia32_vcvttsd2usi32:
1957   case X86::BI__builtin_ia32_vcvttsd2usi64:
1958   case X86::BI__builtin_ia32_vcvttss2si32:
1959   case X86::BI__builtin_ia32_vcvttss2si64:
1960   case X86::BI__builtin_ia32_vcvttss2usi32:
1961   case X86::BI__builtin_ia32_vcvttss2usi64:
1962     ArgNum = 1;
1963     break;
1964   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1965   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1966   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1967   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1968   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1969   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1970   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1971   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1972   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1973   case X86::BI__builtin_ia32_exp2pd_mask:
1974   case X86::BI__builtin_ia32_exp2ps_mask:
1975   case X86::BI__builtin_ia32_getexppd512_mask:
1976   case X86::BI__builtin_ia32_getexpps512_mask:
1977   case X86::BI__builtin_ia32_rcp28pd_mask:
1978   case X86::BI__builtin_ia32_rcp28ps_mask:
1979   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1980   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1981   case X86::BI__builtin_ia32_vcomisd:
1982   case X86::BI__builtin_ia32_vcomiss:
1983   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1984     ArgNum = 3;
1985     break;
1986   case X86::BI__builtin_ia32_cmppd512_mask:
1987   case X86::BI__builtin_ia32_cmpps512_mask:
1988   case X86::BI__builtin_ia32_cmpsd_mask:
1989   case X86::BI__builtin_ia32_cmpss_mask:
1990   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1991   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1992   case X86::BI__builtin_ia32_getexpss128_round_mask:
1993   case X86::BI__builtin_ia32_maxpd512_mask:
1994   case X86::BI__builtin_ia32_maxps512_mask:
1995   case X86::BI__builtin_ia32_maxsd_round_mask:
1996   case X86::BI__builtin_ia32_maxss_round_mask:
1997   case X86::BI__builtin_ia32_minpd512_mask:
1998   case X86::BI__builtin_ia32_minps512_mask:
1999   case X86::BI__builtin_ia32_minsd_round_mask:
2000   case X86::BI__builtin_ia32_minss_round_mask:
2001   case X86::BI__builtin_ia32_rcp28sd_round_mask:
2002   case X86::BI__builtin_ia32_rcp28ss_round_mask:
2003   case X86::BI__builtin_ia32_reducepd512_mask:
2004   case X86::BI__builtin_ia32_reduceps512_mask:
2005   case X86::BI__builtin_ia32_rndscalepd_mask:
2006   case X86::BI__builtin_ia32_rndscaleps_mask:
2007   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2008   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2009     ArgNum = 4;
2010     break;
2011   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2012   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2013   case X86::BI__builtin_ia32_fixupimmps512_mask:
2014   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2015   case X86::BI__builtin_ia32_fixupimmsd_mask:
2016   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2017   case X86::BI__builtin_ia32_fixupimmss_mask:
2018   case X86::BI__builtin_ia32_fixupimmss_maskz:
2019   case X86::BI__builtin_ia32_rangepd512_mask:
2020   case X86::BI__builtin_ia32_rangeps512_mask:
2021   case X86::BI__builtin_ia32_rangesd128_round_mask:
2022   case X86::BI__builtin_ia32_rangess128_round_mask:
2023   case X86::BI__builtin_ia32_reducesd_mask:
2024   case X86::BI__builtin_ia32_reducess_mask:
2025   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2026   case X86::BI__builtin_ia32_rndscaless_round_mask:
2027     ArgNum = 5;
2028     break;
2029   case X86::BI__builtin_ia32_vcvtsd2si64:
2030   case X86::BI__builtin_ia32_vcvtsd2si32:
2031   case X86::BI__builtin_ia32_vcvtsd2usi32:
2032   case X86::BI__builtin_ia32_vcvtsd2usi64:
2033   case X86::BI__builtin_ia32_vcvtss2si32:
2034   case X86::BI__builtin_ia32_vcvtss2si64:
2035   case X86::BI__builtin_ia32_vcvtss2usi32:
2036   case X86::BI__builtin_ia32_vcvtss2usi64:
2037     ArgNum = 1;
2038     HasRC = true;
2039     break;
2040   case X86::BI__builtin_ia32_cvtsi2sd64:
2041   case X86::BI__builtin_ia32_cvtsi2ss32:
2042   case X86::BI__builtin_ia32_cvtsi2ss64:
2043   case X86::BI__builtin_ia32_cvtusi2sd64:
2044   case X86::BI__builtin_ia32_cvtusi2ss32:
2045   case X86::BI__builtin_ia32_cvtusi2ss64:
2046     ArgNum = 2;
2047     HasRC = true;
2048     break;
2049   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2050   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2051   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2052   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2053   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2054   case X86::BI__builtin_ia32_cvtps2qq512_mask:
2055   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2056   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2057   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2058   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2059   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2060   case X86::BI__builtin_ia32_sqrtpd512_mask:
2061   case X86::BI__builtin_ia32_sqrtps512_mask:
2062     ArgNum = 3;
2063     HasRC = true;
2064     break;
2065   case X86::BI__builtin_ia32_addpd512_mask:
2066   case X86::BI__builtin_ia32_addps512_mask:
2067   case X86::BI__builtin_ia32_divpd512_mask:
2068   case X86::BI__builtin_ia32_divps512_mask:
2069   case X86::BI__builtin_ia32_mulpd512_mask:
2070   case X86::BI__builtin_ia32_mulps512_mask:
2071   case X86::BI__builtin_ia32_subpd512_mask:
2072   case X86::BI__builtin_ia32_subps512_mask:
2073   case X86::BI__builtin_ia32_addss_round_mask:
2074   case X86::BI__builtin_ia32_addsd_round_mask:
2075   case X86::BI__builtin_ia32_divss_round_mask:
2076   case X86::BI__builtin_ia32_divsd_round_mask:
2077   case X86::BI__builtin_ia32_mulss_round_mask:
2078   case X86::BI__builtin_ia32_mulsd_round_mask:
2079   case X86::BI__builtin_ia32_subss_round_mask:
2080   case X86::BI__builtin_ia32_subsd_round_mask:
2081   case X86::BI__builtin_ia32_scalefpd512_mask:
2082   case X86::BI__builtin_ia32_scalefps512_mask:
2083   case X86::BI__builtin_ia32_scalefsd_round_mask:
2084   case X86::BI__builtin_ia32_scalefss_round_mask:
2085   case X86::BI__builtin_ia32_getmantpd512_mask:
2086   case X86::BI__builtin_ia32_getmantps512_mask:
2087   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2088   case X86::BI__builtin_ia32_sqrtsd_round_mask:
2089   case X86::BI__builtin_ia32_sqrtss_round_mask:
2090   case X86::BI__builtin_ia32_vfmaddpd512_mask:
2091   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2092   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2093   case X86::BI__builtin_ia32_vfmaddps512_mask:
2094   case X86::BI__builtin_ia32_vfmaddps512_mask3:
2095   case X86::BI__builtin_ia32_vfmaddps512_maskz:
2096   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2097   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2098   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2099   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2100   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2101   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2102   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2103   case X86::BI__builtin_ia32_vfmsubps512_mask3:
2104   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2105   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2106   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2107   case X86::BI__builtin_ia32_vfnmaddps512_mask:
2108   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2109   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2110   case X86::BI__builtin_ia32_vfnmsubps512_mask:
2111   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2112   case X86::BI__builtin_ia32_vfmaddsd3_mask:
2113   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2114   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2115   case X86::BI__builtin_ia32_vfmaddss3_mask:
2116   case X86::BI__builtin_ia32_vfmaddss3_maskz:
2117   case X86::BI__builtin_ia32_vfmaddss3_mask3:
2118     ArgNum = 4;
2119     HasRC = true;
2120     break;
2121   case X86::BI__builtin_ia32_getmantsd_round_mask:
2122   case X86::BI__builtin_ia32_getmantss_round_mask:
2123     ArgNum = 5;
2124     HasRC = true;
2125     break;
2126   }
2127 
2128   llvm::APSInt Result;
2129 
2130   // We can't check the value of a dependent argument.
2131   Expr *Arg = TheCall->getArg(ArgNum);
2132   if (Arg->isTypeDependent() || Arg->isValueDependent())
2133     return false;
2134 
2135   // Check constant-ness first.
2136   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2137     return true;
2138 
2139   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2140   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2141   // combined with ROUND_NO_EXC.
2142   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2143       Result == 8/*ROUND_NO_EXC*/ ||
2144       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2145     return false;
2146 
2147   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2148     << Arg->getSourceRange();
2149 }
2150 
2151 // Check if the gather/scatter scale is legal.
2152 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2153                                              CallExpr *TheCall) {
2154   unsigned ArgNum = 0;
2155   switch (BuiltinID) {
2156   default:
2157     return false;
2158   case X86::BI__builtin_ia32_gatherpfdpd:
2159   case X86::BI__builtin_ia32_gatherpfdps:
2160   case X86::BI__builtin_ia32_gatherpfqpd:
2161   case X86::BI__builtin_ia32_gatherpfqps:
2162   case X86::BI__builtin_ia32_scatterpfdpd:
2163   case X86::BI__builtin_ia32_scatterpfdps:
2164   case X86::BI__builtin_ia32_scatterpfqpd:
2165   case X86::BI__builtin_ia32_scatterpfqps:
2166     ArgNum = 3;
2167     break;
2168   case X86::BI__builtin_ia32_gatherd_pd:
2169   case X86::BI__builtin_ia32_gatherd_pd256:
2170   case X86::BI__builtin_ia32_gatherq_pd:
2171   case X86::BI__builtin_ia32_gatherq_pd256:
2172   case X86::BI__builtin_ia32_gatherd_ps:
2173   case X86::BI__builtin_ia32_gatherd_ps256:
2174   case X86::BI__builtin_ia32_gatherq_ps:
2175   case X86::BI__builtin_ia32_gatherq_ps256:
2176   case X86::BI__builtin_ia32_gatherd_q:
2177   case X86::BI__builtin_ia32_gatherd_q256:
2178   case X86::BI__builtin_ia32_gatherq_q:
2179   case X86::BI__builtin_ia32_gatherq_q256:
2180   case X86::BI__builtin_ia32_gatherd_d:
2181   case X86::BI__builtin_ia32_gatherd_d256:
2182   case X86::BI__builtin_ia32_gatherq_d:
2183   case X86::BI__builtin_ia32_gatherq_d256:
2184   case X86::BI__builtin_ia32_gather3div2df:
2185   case X86::BI__builtin_ia32_gather3div2di:
2186   case X86::BI__builtin_ia32_gather3div4df:
2187   case X86::BI__builtin_ia32_gather3div4di:
2188   case X86::BI__builtin_ia32_gather3div4sf:
2189   case X86::BI__builtin_ia32_gather3div4si:
2190   case X86::BI__builtin_ia32_gather3div8sf:
2191   case X86::BI__builtin_ia32_gather3div8si:
2192   case X86::BI__builtin_ia32_gather3siv2df:
2193   case X86::BI__builtin_ia32_gather3siv2di:
2194   case X86::BI__builtin_ia32_gather3siv4df:
2195   case X86::BI__builtin_ia32_gather3siv4di:
2196   case X86::BI__builtin_ia32_gather3siv4sf:
2197   case X86::BI__builtin_ia32_gather3siv4si:
2198   case X86::BI__builtin_ia32_gather3siv8sf:
2199   case X86::BI__builtin_ia32_gather3siv8si:
2200   case X86::BI__builtin_ia32_gathersiv8df:
2201   case X86::BI__builtin_ia32_gathersiv16sf:
2202   case X86::BI__builtin_ia32_gatherdiv8df:
2203   case X86::BI__builtin_ia32_gatherdiv16sf:
2204   case X86::BI__builtin_ia32_gathersiv8di:
2205   case X86::BI__builtin_ia32_gathersiv16si:
2206   case X86::BI__builtin_ia32_gatherdiv8di:
2207   case X86::BI__builtin_ia32_gatherdiv16si:
2208   case X86::BI__builtin_ia32_scatterdiv2df:
2209   case X86::BI__builtin_ia32_scatterdiv2di:
2210   case X86::BI__builtin_ia32_scatterdiv4df:
2211   case X86::BI__builtin_ia32_scatterdiv4di:
2212   case X86::BI__builtin_ia32_scatterdiv4sf:
2213   case X86::BI__builtin_ia32_scatterdiv4si:
2214   case X86::BI__builtin_ia32_scatterdiv8sf:
2215   case X86::BI__builtin_ia32_scatterdiv8si:
2216   case X86::BI__builtin_ia32_scattersiv2df:
2217   case X86::BI__builtin_ia32_scattersiv2di:
2218   case X86::BI__builtin_ia32_scattersiv4df:
2219   case X86::BI__builtin_ia32_scattersiv4di:
2220   case X86::BI__builtin_ia32_scattersiv4sf:
2221   case X86::BI__builtin_ia32_scattersiv4si:
2222   case X86::BI__builtin_ia32_scattersiv8sf:
2223   case X86::BI__builtin_ia32_scattersiv8si:
2224   case X86::BI__builtin_ia32_scattersiv8df:
2225   case X86::BI__builtin_ia32_scattersiv16sf:
2226   case X86::BI__builtin_ia32_scatterdiv8df:
2227   case X86::BI__builtin_ia32_scatterdiv16sf:
2228   case X86::BI__builtin_ia32_scattersiv8di:
2229   case X86::BI__builtin_ia32_scattersiv16si:
2230   case X86::BI__builtin_ia32_scatterdiv8di:
2231   case X86::BI__builtin_ia32_scatterdiv16si:
2232     ArgNum = 4;
2233     break;
2234   }
2235 
2236   llvm::APSInt Result;
2237 
2238   // We can't check the value of a dependent argument.
2239   Expr *Arg = TheCall->getArg(ArgNum);
2240   if (Arg->isTypeDependent() || Arg->isValueDependent())
2241     return false;
2242 
2243   // Check constant-ness first.
2244   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2245     return true;
2246 
2247   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2248     return false;
2249 
2250   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2251     << Arg->getSourceRange();
2252 }
2253 
2254 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2255   if (BuiltinID == X86::BI__builtin_cpu_supports)
2256     return SemaBuiltinCpuSupports(*this, TheCall);
2257 
2258   if (BuiltinID == X86::BI__builtin_cpu_is)
2259     return SemaBuiltinCpuIs(*this, TheCall);
2260 
2261   // If the intrinsic has rounding or SAE make sure its valid.
2262   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2263     return true;
2264 
2265   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2266   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2267     return true;
2268 
2269   // For intrinsics which take an immediate value as part of the instruction,
2270   // range check them here.
2271   int i = 0, l = 0, u = 0;
2272   switch (BuiltinID) {
2273   default:
2274     return false;
2275   case X86::BI_mm_prefetch:
2276     i = 1; l = 0; u = 7;
2277     break;
2278   case X86::BI__builtin_ia32_sha1rnds4:
2279   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2280   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2281   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2282   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2283     i = 2; l = 0; u = 3;
2284     break;
2285   case X86::BI__builtin_ia32_vpermil2pd:
2286   case X86::BI__builtin_ia32_vpermil2pd256:
2287   case X86::BI__builtin_ia32_vpermil2ps:
2288   case X86::BI__builtin_ia32_vpermil2ps256:
2289     i = 3; l = 0; u = 3;
2290     break;
2291   case X86::BI__builtin_ia32_cmpb128_mask:
2292   case X86::BI__builtin_ia32_cmpw128_mask:
2293   case X86::BI__builtin_ia32_cmpd128_mask:
2294   case X86::BI__builtin_ia32_cmpq128_mask:
2295   case X86::BI__builtin_ia32_cmpb256_mask:
2296   case X86::BI__builtin_ia32_cmpw256_mask:
2297   case X86::BI__builtin_ia32_cmpd256_mask:
2298   case X86::BI__builtin_ia32_cmpq256_mask:
2299   case X86::BI__builtin_ia32_cmpb512_mask:
2300   case X86::BI__builtin_ia32_cmpw512_mask:
2301   case X86::BI__builtin_ia32_cmpd512_mask:
2302   case X86::BI__builtin_ia32_cmpq512_mask:
2303   case X86::BI__builtin_ia32_ucmpb128_mask:
2304   case X86::BI__builtin_ia32_ucmpw128_mask:
2305   case X86::BI__builtin_ia32_ucmpd128_mask:
2306   case X86::BI__builtin_ia32_ucmpq128_mask:
2307   case X86::BI__builtin_ia32_ucmpb256_mask:
2308   case X86::BI__builtin_ia32_ucmpw256_mask:
2309   case X86::BI__builtin_ia32_ucmpd256_mask:
2310   case X86::BI__builtin_ia32_ucmpq256_mask:
2311   case X86::BI__builtin_ia32_ucmpb512_mask:
2312   case X86::BI__builtin_ia32_ucmpw512_mask:
2313   case X86::BI__builtin_ia32_ucmpd512_mask:
2314   case X86::BI__builtin_ia32_ucmpq512_mask:
2315   case X86::BI__builtin_ia32_vpcomub:
2316   case X86::BI__builtin_ia32_vpcomuw:
2317   case X86::BI__builtin_ia32_vpcomud:
2318   case X86::BI__builtin_ia32_vpcomuq:
2319   case X86::BI__builtin_ia32_vpcomb:
2320   case X86::BI__builtin_ia32_vpcomw:
2321   case X86::BI__builtin_ia32_vpcomd:
2322   case X86::BI__builtin_ia32_vpcomq:
2323     i = 2; l = 0; u = 7;
2324     break;
2325   case X86::BI__builtin_ia32_roundps:
2326   case X86::BI__builtin_ia32_roundpd:
2327   case X86::BI__builtin_ia32_roundps256:
2328   case X86::BI__builtin_ia32_roundpd256:
2329     i = 1; l = 0; u = 15;
2330     break;
2331   case X86::BI__builtin_ia32_roundss:
2332   case X86::BI__builtin_ia32_roundsd:
2333   case X86::BI__builtin_ia32_rangepd128_mask:
2334   case X86::BI__builtin_ia32_rangepd256_mask:
2335   case X86::BI__builtin_ia32_rangepd512_mask:
2336   case X86::BI__builtin_ia32_rangeps128_mask:
2337   case X86::BI__builtin_ia32_rangeps256_mask:
2338   case X86::BI__builtin_ia32_rangeps512_mask:
2339   case X86::BI__builtin_ia32_getmantsd_round_mask:
2340   case X86::BI__builtin_ia32_getmantss_round_mask:
2341     i = 2; l = 0; u = 15;
2342     break;
2343   case X86::BI__builtin_ia32_cmpps:
2344   case X86::BI__builtin_ia32_cmpss:
2345   case X86::BI__builtin_ia32_cmppd:
2346   case X86::BI__builtin_ia32_cmpsd:
2347   case X86::BI__builtin_ia32_cmpps256:
2348   case X86::BI__builtin_ia32_cmppd256:
2349   case X86::BI__builtin_ia32_cmpps128_mask:
2350   case X86::BI__builtin_ia32_cmppd128_mask:
2351   case X86::BI__builtin_ia32_cmpps256_mask:
2352   case X86::BI__builtin_ia32_cmppd256_mask:
2353   case X86::BI__builtin_ia32_cmpps512_mask:
2354   case X86::BI__builtin_ia32_cmppd512_mask:
2355   case X86::BI__builtin_ia32_cmpsd_mask:
2356   case X86::BI__builtin_ia32_cmpss_mask:
2357     i = 2; l = 0; u = 31;
2358     break;
2359   case X86::BI__builtin_ia32_vcvtps2ph:
2360   case X86::BI__builtin_ia32_vcvtps2ph_mask:
2361   case X86::BI__builtin_ia32_vcvtps2ph256:
2362   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2363   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2364   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2365   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2366   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2367   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2368   case X86::BI__builtin_ia32_rndscaleps_mask:
2369   case X86::BI__builtin_ia32_rndscalepd_mask:
2370   case X86::BI__builtin_ia32_reducepd128_mask:
2371   case X86::BI__builtin_ia32_reducepd256_mask:
2372   case X86::BI__builtin_ia32_reducepd512_mask:
2373   case X86::BI__builtin_ia32_reduceps128_mask:
2374   case X86::BI__builtin_ia32_reduceps256_mask:
2375   case X86::BI__builtin_ia32_reduceps512_mask:
2376   case X86::BI__builtin_ia32_prold512_mask:
2377   case X86::BI__builtin_ia32_prolq512_mask:
2378   case X86::BI__builtin_ia32_prold128_mask:
2379   case X86::BI__builtin_ia32_prold256_mask:
2380   case X86::BI__builtin_ia32_prolq128_mask:
2381   case X86::BI__builtin_ia32_prolq256_mask:
2382   case X86::BI__builtin_ia32_prord128_mask:
2383   case X86::BI__builtin_ia32_prord256_mask:
2384   case X86::BI__builtin_ia32_prorq128_mask:
2385   case X86::BI__builtin_ia32_prorq256_mask:
2386   case X86::BI__builtin_ia32_fpclasspd128_mask:
2387   case X86::BI__builtin_ia32_fpclasspd256_mask:
2388   case X86::BI__builtin_ia32_fpclassps128_mask:
2389   case X86::BI__builtin_ia32_fpclassps256_mask:
2390   case X86::BI__builtin_ia32_fpclassps512_mask:
2391   case X86::BI__builtin_ia32_fpclasspd512_mask:
2392   case X86::BI__builtin_ia32_fpclasssd_mask:
2393   case X86::BI__builtin_ia32_fpclassss_mask:
2394     i = 1; l = 0; u = 255;
2395     break;
2396   case X86::BI__builtin_ia32_palignr128:
2397   case X86::BI__builtin_ia32_palignr256:
2398   case X86::BI__builtin_ia32_palignr512_mask:
2399   case X86::BI__builtin_ia32_vcomisd:
2400   case X86::BI__builtin_ia32_vcomiss:
2401   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2402   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2403   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2404   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2405   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2406   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2407   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2408   case X86::BI__builtin_ia32_vpshldd128_mask:
2409   case X86::BI__builtin_ia32_vpshldd256_mask:
2410   case X86::BI__builtin_ia32_vpshldd512_mask:
2411   case X86::BI__builtin_ia32_vpshldq128_mask:
2412   case X86::BI__builtin_ia32_vpshldq256_mask:
2413   case X86::BI__builtin_ia32_vpshldq512_mask:
2414   case X86::BI__builtin_ia32_vpshldw128_mask:
2415   case X86::BI__builtin_ia32_vpshldw256_mask:
2416   case X86::BI__builtin_ia32_vpshldw512_mask:
2417   case X86::BI__builtin_ia32_vpshrdd128_mask:
2418   case X86::BI__builtin_ia32_vpshrdd256_mask:
2419   case X86::BI__builtin_ia32_vpshrdd512_mask:
2420   case X86::BI__builtin_ia32_vpshrdq128_mask:
2421   case X86::BI__builtin_ia32_vpshrdq256_mask:
2422   case X86::BI__builtin_ia32_vpshrdq512_mask:
2423   case X86::BI__builtin_ia32_vpshrdw128_mask:
2424   case X86::BI__builtin_ia32_vpshrdw256_mask:
2425   case X86::BI__builtin_ia32_vpshrdw512_mask:
2426     i = 2; l = 0; u = 255;
2427     break;
2428   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2429   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2430   case X86::BI__builtin_ia32_fixupimmps512_mask:
2431   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2432   case X86::BI__builtin_ia32_fixupimmsd_mask:
2433   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2434   case X86::BI__builtin_ia32_fixupimmss_mask:
2435   case X86::BI__builtin_ia32_fixupimmss_maskz:
2436   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2437   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2438   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2439   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2440   case X86::BI__builtin_ia32_fixupimmps128_mask:
2441   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2442   case X86::BI__builtin_ia32_fixupimmps256_mask:
2443   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2444   case X86::BI__builtin_ia32_pternlogd512_mask:
2445   case X86::BI__builtin_ia32_pternlogd512_maskz:
2446   case X86::BI__builtin_ia32_pternlogq512_mask:
2447   case X86::BI__builtin_ia32_pternlogq512_maskz:
2448   case X86::BI__builtin_ia32_pternlogd128_mask:
2449   case X86::BI__builtin_ia32_pternlogd128_maskz:
2450   case X86::BI__builtin_ia32_pternlogd256_mask:
2451   case X86::BI__builtin_ia32_pternlogd256_maskz:
2452   case X86::BI__builtin_ia32_pternlogq128_mask:
2453   case X86::BI__builtin_ia32_pternlogq128_maskz:
2454   case X86::BI__builtin_ia32_pternlogq256_mask:
2455   case X86::BI__builtin_ia32_pternlogq256_maskz:
2456     i = 3; l = 0; u = 255;
2457     break;
2458   case X86::BI__builtin_ia32_gatherpfdpd:
2459   case X86::BI__builtin_ia32_gatherpfdps:
2460   case X86::BI__builtin_ia32_gatherpfqpd:
2461   case X86::BI__builtin_ia32_gatherpfqps:
2462   case X86::BI__builtin_ia32_scatterpfdpd:
2463   case X86::BI__builtin_ia32_scatterpfdps:
2464   case X86::BI__builtin_ia32_scatterpfqpd:
2465   case X86::BI__builtin_ia32_scatterpfqps:
2466     i = 4; l = 2; u = 3;
2467     break;
2468   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2469   case X86::BI__builtin_ia32_rndscaless_round_mask:
2470     i = 4; l = 0; u = 255;
2471     break;
2472   }
2473   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2474 }
2475 
2476 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2477 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2478 /// Returns true when the format fits the function and the FormatStringInfo has
2479 /// been populated.
2480 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2481                                FormatStringInfo *FSI) {
2482   FSI->HasVAListArg = Format->getFirstArg() == 0;
2483   FSI->FormatIdx = Format->getFormatIdx() - 1;
2484   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2485 
2486   // The way the format attribute works in GCC, the implicit this argument
2487   // of member functions is counted. However, it doesn't appear in our own
2488   // lists, so decrement format_idx in that case.
2489   if (IsCXXMember) {
2490     if(FSI->FormatIdx == 0)
2491       return false;
2492     --FSI->FormatIdx;
2493     if (FSI->FirstDataArg != 0)
2494       --FSI->FirstDataArg;
2495   }
2496   return true;
2497 }
2498 
2499 /// Checks if a the given expression evaluates to null.
2500 ///
2501 /// \brief Returns true if the value evaluates to null.
2502 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2503   // If the expression has non-null type, it doesn't evaluate to null.
2504   if (auto nullability
2505         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2506     if (*nullability == NullabilityKind::NonNull)
2507       return false;
2508   }
2509 
2510   // As a special case, transparent unions initialized with zero are
2511   // considered null for the purposes of the nonnull attribute.
2512   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2513     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2514       if (const CompoundLiteralExpr *CLE =
2515           dyn_cast<CompoundLiteralExpr>(Expr))
2516         if (const InitListExpr *ILE =
2517             dyn_cast<InitListExpr>(CLE->getInitializer()))
2518           Expr = ILE->getInit(0);
2519   }
2520 
2521   bool Result;
2522   return (!Expr->isValueDependent() &&
2523           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2524           !Result);
2525 }
2526 
2527 static void CheckNonNullArgument(Sema &S,
2528                                  const Expr *ArgExpr,
2529                                  SourceLocation CallSiteLoc) {
2530   if (CheckNonNullExpr(S, ArgExpr))
2531     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2532            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2533 }
2534 
2535 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2536   FormatStringInfo FSI;
2537   if ((GetFormatStringType(Format) == FST_NSString) &&
2538       getFormatStringInfo(Format, false, &FSI)) {
2539     Idx = FSI.FormatIdx;
2540     return true;
2541   }
2542   return false;
2543 }
2544 
2545 /// \brief Diagnose use of %s directive in an NSString which is being passed
2546 /// as formatting string to formatting method.
2547 static void
2548 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2549                                         const NamedDecl *FDecl,
2550                                         Expr **Args,
2551                                         unsigned NumArgs) {
2552   unsigned Idx = 0;
2553   bool Format = false;
2554   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2555   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2556     Idx = 2;
2557     Format = true;
2558   }
2559   else
2560     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2561       if (S.GetFormatNSStringIdx(I, Idx)) {
2562         Format = true;
2563         break;
2564       }
2565     }
2566   if (!Format || NumArgs <= Idx)
2567     return;
2568   const Expr *FormatExpr = Args[Idx];
2569   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2570     FormatExpr = CSCE->getSubExpr();
2571   const StringLiteral *FormatString;
2572   if (const ObjCStringLiteral *OSL =
2573       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2574     FormatString = OSL->getString();
2575   else
2576     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2577   if (!FormatString)
2578     return;
2579   if (S.FormatStringHasSArg(FormatString)) {
2580     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2581       << "%s" << 1 << 1;
2582     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2583       << FDecl->getDeclName();
2584   }
2585 }
2586 
2587 /// Determine whether the given type has a non-null nullability annotation.
2588 static bool isNonNullType(ASTContext &ctx, QualType type) {
2589   if (auto nullability = type->getNullability(ctx))
2590     return *nullability == NullabilityKind::NonNull;
2591 
2592   return false;
2593 }
2594 
2595 static void CheckNonNullArguments(Sema &S,
2596                                   const NamedDecl *FDecl,
2597                                   const FunctionProtoType *Proto,
2598                                   ArrayRef<const Expr *> Args,
2599                                   SourceLocation CallSiteLoc) {
2600   assert((FDecl || Proto) && "Need a function declaration or prototype");
2601 
2602   // Check the attributes attached to the method/function itself.
2603   llvm::SmallBitVector NonNullArgs;
2604   if (FDecl) {
2605     // Handle the nonnull attribute on the function/method declaration itself.
2606     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2607       if (!NonNull->args_size()) {
2608         // Easy case: all pointer arguments are nonnull.
2609         for (const auto *Arg : Args)
2610           if (S.isValidPointerAttrType(Arg->getType()))
2611             CheckNonNullArgument(S, Arg, CallSiteLoc);
2612         return;
2613       }
2614 
2615       for (const ParamIdx &Idx : NonNull->args()) {
2616         unsigned IdxAST = Idx.getASTIndex();
2617         if (IdxAST >= Args.size())
2618           continue;
2619         if (NonNullArgs.empty())
2620           NonNullArgs.resize(Args.size());
2621         NonNullArgs.set(IdxAST);
2622       }
2623     }
2624   }
2625 
2626   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2627     // Handle the nonnull attribute on the parameters of the
2628     // function/method.
2629     ArrayRef<ParmVarDecl*> parms;
2630     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2631       parms = FD->parameters();
2632     else
2633       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2634 
2635     unsigned ParamIndex = 0;
2636     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2637          I != E; ++I, ++ParamIndex) {
2638       const ParmVarDecl *PVD = *I;
2639       if (PVD->hasAttr<NonNullAttr>() ||
2640           isNonNullType(S.Context, PVD->getType())) {
2641         if (NonNullArgs.empty())
2642           NonNullArgs.resize(Args.size());
2643 
2644         NonNullArgs.set(ParamIndex);
2645       }
2646     }
2647   } else {
2648     // If we have a non-function, non-method declaration but no
2649     // function prototype, try to dig out the function prototype.
2650     if (!Proto) {
2651       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2652         QualType type = VD->getType().getNonReferenceType();
2653         if (auto pointerType = type->getAs<PointerType>())
2654           type = pointerType->getPointeeType();
2655         else if (auto blockType = type->getAs<BlockPointerType>())
2656           type = blockType->getPointeeType();
2657         // FIXME: data member pointers?
2658 
2659         // Dig out the function prototype, if there is one.
2660         Proto = type->getAs<FunctionProtoType>();
2661       }
2662     }
2663 
2664     // Fill in non-null argument information from the nullability
2665     // information on the parameter types (if we have them).
2666     if (Proto) {
2667       unsigned Index = 0;
2668       for (auto paramType : Proto->getParamTypes()) {
2669         if (isNonNullType(S.Context, paramType)) {
2670           if (NonNullArgs.empty())
2671             NonNullArgs.resize(Args.size());
2672 
2673           NonNullArgs.set(Index);
2674         }
2675 
2676         ++Index;
2677       }
2678     }
2679   }
2680 
2681   // Check for non-null arguments.
2682   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2683        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2684     if (NonNullArgs[ArgIndex])
2685       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2686   }
2687 }
2688 
2689 /// Handles the checks for format strings, non-POD arguments to vararg
2690 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2691 /// attributes.
2692 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2693                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
2694                      bool IsMemberFunction, SourceLocation Loc,
2695                      SourceRange Range, VariadicCallType CallType) {
2696   // FIXME: We should check as much as we can in the template definition.
2697   if (CurContext->isDependentContext())
2698     return;
2699 
2700   // Printf and scanf checking.
2701   llvm::SmallBitVector CheckedVarArgs;
2702   if (FDecl) {
2703     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2704       // Only create vector if there are format attributes.
2705       CheckedVarArgs.resize(Args.size());
2706 
2707       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2708                            CheckedVarArgs);
2709     }
2710   }
2711 
2712   // Refuse POD arguments that weren't caught by the format string
2713   // checks above.
2714   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2715   if (CallType != VariadicDoesNotApply &&
2716       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2717     unsigned NumParams = Proto ? Proto->getNumParams()
2718                        : FDecl && isa<FunctionDecl>(FDecl)
2719                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2720                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2721                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2722                        : 0;
2723 
2724     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2725       // Args[ArgIdx] can be null in malformed code.
2726       if (const Expr *Arg = Args[ArgIdx]) {
2727         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2728           checkVariadicArgument(Arg, CallType);
2729       }
2730     }
2731   }
2732 
2733   if (FDecl || Proto) {
2734     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2735 
2736     // Type safety checking.
2737     if (FDecl) {
2738       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2739         CheckArgumentWithTypeTag(I, Args, Loc);
2740     }
2741   }
2742 
2743   if (FD)
2744     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2745 }
2746 
2747 /// CheckConstructorCall - Check a constructor call for correctness and safety
2748 /// properties not enforced by the C type system.
2749 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2750                                 ArrayRef<const Expr *> Args,
2751                                 const FunctionProtoType *Proto,
2752                                 SourceLocation Loc) {
2753   VariadicCallType CallType =
2754     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2755   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2756             Loc, SourceRange(), CallType);
2757 }
2758 
2759 /// CheckFunctionCall - Check a direct function call for various correctness
2760 /// and safety properties not strictly enforced by the C type system.
2761 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2762                              const FunctionProtoType *Proto) {
2763   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2764                               isa<CXXMethodDecl>(FDecl);
2765   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2766                           IsMemberOperatorCall;
2767   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2768                                                   TheCall->getCallee());
2769   Expr** Args = TheCall->getArgs();
2770   unsigned NumArgs = TheCall->getNumArgs();
2771 
2772   Expr *ImplicitThis = nullptr;
2773   if (IsMemberOperatorCall) {
2774     // If this is a call to a member operator, hide the first argument
2775     // from checkCall.
2776     // FIXME: Our choice of AST representation here is less than ideal.
2777     ImplicitThis = Args[0];
2778     ++Args;
2779     --NumArgs;
2780   } else if (IsMemberFunction)
2781     ImplicitThis =
2782         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2783 
2784   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2785             IsMemberFunction, TheCall->getRParenLoc(),
2786             TheCall->getCallee()->getSourceRange(), CallType);
2787 
2788   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2789   // None of the checks below are needed for functions that don't have
2790   // simple names (e.g., C++ conversion functions).
2791   if (!FnInfo)
2792     return false;
2793 
2794   CheckAbsoluteValueFunction(TheCall, FDecl);
2795   CheckMaxUnsignedZero(TheCall, FDecl);
2796 
2797   if (getLangOpts().ObjC1)
2798     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2799 
2800   unsigned CMId = FDecl->getMemoryFunctionKind();
2801   if (CMId == 0)
2802     return false;
2803 
2804   // Handle memory setting and copying functions.
2805   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2806     CheckStrlcpycatArguments(TheCall, FnInfo);
2807   else if (CMId == Builtin::BIstrncat)
2808     CheckStrncatArguments(TheCall, FnInfo);
2809   else
2810     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2811 
2812   return false;
2813 }
2814 
2815 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2816                                ArrayRef<const Expr *> Args) {
2817   VariadicCallType CallType =
2818       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2819 
2820   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2821             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2822             CallType);
2823 
2824   return false;
2825 }
2826 
2827 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2828                             const FunctionProtoType *Proto) {
2829   QualType Ty;
2830   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2831     Ty = V->getType().getNonReferenceType();
2832   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2833     Ty = F->getType().getNonReferenceType();
2834   else
2835     return false;
2836 
2837   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2838       !Ty->isFunctionProtoType())
2839     return false;
2840 
2841   VariadicCallType CallType;
2842   if (!Proto || !Proto->isVariadic()) {
2843     CallType = VariadicDoesNotApply;
2844   } else if (Ty->isBlockPointerType()) {
2845     CallType = VariadicBlock;
2846   } else { // Ty->isFunctionPointerType()
2847     CallType = VariadicFunction;
2848   }
2849 
2850   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2851             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2852             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2853             TheCall->getCallee()->getSourceRange(), CallType);
2854 
2855   return false;
2856 }
2857 
2858 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2859 /// such as function pointers returned from functions.
2860 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2861   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2862                                                   TheCall->getCallee());
2863   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2864             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2865             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2866             TheCall->getCallee()->getSourceRange(), CallType);
2867 
2868   return false;
2869 }
2870 
2871 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2872   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2873     return false;
2874 
2875   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2876   switch (Op) {
2877   case AtomicExpr::AO__c11_atomic_init:
2878   case AtomicExpr::AO__opencl_atomic_init:
2879     llvm_unreachable("There is no ordering argument for an init");
2880 
2881   case AtomicExpr::AO__c11_atomic_load:
2882   case AtomicExpr::AO__opencl_atomic_load:
2883   case AtomicExpr::AO__atomic_load_n:
2884   case AtomicExpr::AO__atomic_load:
2885     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2886            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2887 
2888   case AtomicExpr::AO__c11_atomic_store:
2889   case AtomicExpr::AO__opencl_atomic_store:
2890   case AtomicExpr::AO__atomic_store:
2891   case AtomicExpr::AO__atomic_store_n:
2892     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2893            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2894            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2895 
2896   default:
2897     return true;
2898   }
2899 }
2900 
2901 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2902                                          AtomicExpr::AtomicOp Op) {
2903   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2904   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2905 
2906   // All the non-OpenCL operations take one of the following forms.
2907   // The OpenCL operations take the __c11 forms with one extra argument for
2908   // synchronization scope.
2909   enum {
2910     // C    __c11_atomic_init(A *, C)
2911     Init,
2912 
2913     // C    __c11_atomic_load(A *, int)
2914     Load,
2915 
2916     // void __atomic_load(A *, CP, int)
2917     LoadCopy,
2918 
2919     // void __atomic_store(A *, CP, int)
2920     Copy,
2921 
2922     // C    __c11_atomic_add(A *, M, int)
2923     Arithmetic,
2924 
2925     // C    __atomic_exchange_n(A *, CP, int)
2926     Xchg,
2927 
2928     // void __atomic_exchange(A *, C *, CP, int)
2929     GNUXchg,
2930 
2931     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2932     C11CmpXchg,
2933 
2934     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2935     GNUCmpXchg
2936   } Form = Init;
2937 
2938   const unsigned NumForm = GNUCmpXchg + 1;
2939   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2940   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2941   // where:
2942   //   C is an appropriate type,
2943   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2944   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2945   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2946   //   the int parameters are for orderings.
2947 
2948   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2949       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2950       "need to update code for modified forms");
2951   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2952                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2953                         AtomicExpr::AO__atomic_load,
2954                 "need to update code for modified C11 atomics");
2955   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2956                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2957   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2958                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2959                IsOpenCL;
2960   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2961              Op == AtomicExpr::AO__atomic_store_n ||
2962              Op == AtomicExpr::AO__atomic_exchange_n ||
2963              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2964   bool IsAddSub = false;
2965 
2966   switch (Op) {
2967   case AtomicExpr::AO__c11_atomic_init:
2968   case AtomicExpr::AO__opencl_atomic_init:
2969     Form = Init;
2970     break;
2971 
2972   case AtomicExpr::AO__c11_atomic_load:
2973   case AtomicExpr::AO__opencl_atomic_load:
2974   case AtomicExpr::AO__atomic_load_n:
2975     Form = Load;
2976     break;
2977 
2978   case AtomicExpr::AO__atomic_load:
2979     Form = LoadCopy;
2980     break;
2981 
2982   case AtomicExpr::AO__c11_atomic_store:
2983   case AtomicExpr::AO__opencl_atomic_store:
2984   case AtomicExpr::AO__atomic_store:
2985   case AtomicExpr::AO__atomic_store_n:
2986     Form = Copy;
2987     break;
2988 
2989   case AtomicExpr::AO__c11_atomic_fetch_add:
2990   case AtomicExpr::AO__c11_atomic_fetch_sub:
2991   case AtomicExpr::AO__opencl_atomic_fetch_add:
2992   case AtomicExpr::AO__opencl_atomic_fetch_sub:
2993   case AtomicExpr::AO__opencl_atomic_fetch_min:
2994   case AtomicExpr::AO__opencl_atomic_fetch_max:
2995   case AtomicExpr::AO__atomic_fetch_add:
2996   case AtomicExpr::AO__atomic_fetch_sub:
2997   case AtomicExpr::AO__atomic_add_fetch:
2998   case AtomicExpr::AO__atomic_sub_fetch:
2999     IsAddSub = true;
3000     LLVM_FALLTHROUGH;
3001   case AtomicExpr::AO__c11_atomic_fetch_and:
3002   case AtomicExpr::AO__c11_atomic_fetch_or:
3003   case AtomicExpr::AO__c11_atomic_fetch_xor:
3004   case AtomicExpr::AO__opencl_atomic_fetch_and:
3005   case AtomicExpr::AO__opencl_atomic_fetch_or:
3006   case AtomicExpr::AO__opencl_atomic_fetch_xor:
3007   case AtomicExpr::AO__atomic_fetch_and:
3008   case AtomicExpr::AO__atomic_fetch_or:
3009   case AtomicExpr::AO__atomic_fetch_xor:
3010   case AtomicExpr::AO__atomic_fetch_nand:
3011   case AtomicExpr::AO__atomic_and_fetch:
3012   case AtomicExpr::AO__atomic_or_fetch:
3013   case AtomicExpr::AO__atomic_xor_fetch:
3014   case AtomicExpr::AO__atomic_nand_fetch:
3015     Form = Arithmetic;
3016     break;
3017 
3018   case AtomicExpr::AO__c11_atomic_exchange:
3019   case AtomicExpr::AO__opencl_atomic_exchange:
3020   case AtomicExpr::AO__atomic_exchange_n:
3021     Form = Xchg;
3022     break;
3023 
3024   case AtomicExpr::AO__atomic_exchange:
3025     Form = GNUXchg;
3026     break;
3027 
3028   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3029   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3030   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3031   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3032     Form = C11CmpXchg;
3033     break;
3034 
3035   case AtomicExpr::AO__atomic_compare_exchange:
3036   case AtomicExpr::AO__atomic_compare_exchange_n:
3037     Form = GNUCmpXchg;
3038     break;
3039   }
3040 
3041   unsigned AdjustedNumArgs = NumArgs[Form];
3042   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3043     ++AdjustedNumArgs;
3044   // Check we have the right number of arguments.
3045   if (TheCall->getNumArgs() < AdjustedNumArgs) {
3046     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3047       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3048       << TheCall->getCallee()->getSourceRange();
3049     return ExprError();
3050   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3051     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3052          diag::err_typecheck_call_too_many_args)
3053       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3054       << TheCall->getCallee()->getSourceRange();
3055     return ExprError();
3056   }
3057 
3058   // Inspect the first argument of the atomic operation.
3059   Expr *Ptr = TheCall->getArg(0);
3060   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3061   if (ConvertedPtr.isInvalid())
3062     return ExprError();
3063 
3064   Ptr = ConvertedPtr.get();
3065   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3066   if (!pointerType) {
3067     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3068       << Ptr->getType() << Ptr->getSourceRange();
3069     return ExprError();
3070   }
3071 
3072   // For a __c11 builtin, this should be a pointer to an _Atomic type.
3073   QualType AtomTy = pointerType->getPointeeType(); // 'A'
3074   QualType ValType = AtomTy; // 'C'
3075   if (IsC11) {
3076     if (!AtomTy->isAtomicType()) {
3077       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3078         << Ptr->getType() << Ptr->getSourceRange();
3079       return ExprError();
3080     }
3081     if (AtomTy.isConstQualified() ||
3082         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3083       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3084           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3085           << Ptr->getSourceRange();
3086       return ExprError();
3087     }
3088     ValType = AtomTy->getAs<AtomicType>()->getValueType();
3089   } else if (Form != Load && Form != LoadCopy) {
3090     if (ValType.isConstQualified()) {
3091       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3092         << Ptr->getType() << Ptr->getSourceRange();
3093       return ExprError();
3094     }
3095   }
3096 
3097   // For an arithmetic operation, the implied arithmetic must be well-formed.
3098   if (Form == Arithmetic) {
3099     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3100     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3101       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3102         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3103       return ExprError();
3104     }
3105     if (!IsAddSub && !ValType->isIntegerType()) {
3106       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3107         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3108       return ExprError();
3109     }
3110     if (IsC11 && ValType->isPointerType() &&
3111         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3112                             diag::err_incomplete_type)) {
3113       return ExprError();
3114     }
3115   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3116     // For __atomic_*_n operations, the value type must be a scalar integral or
3117     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3118     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3119       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3120     return ExprError();
3121   }
3122 
3123   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3124       !AtomTy->isScalarType()) {
3125     // For GNU atomics, require a trivially-copyable type. This is not part of
3126     // the GNU atomics specification, but we enforce it for sanity.
3127     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3128       << Ptr->getType() << Ptr->getSourceRange();
3129     return ExprError();
3130   }
3131 
3132   switch (ValType.getObjCLifetime()) {
3133   case Qualifiers::OCL_None:
3134   case Qualifiers::OCL_ExplicitNone:
3135     // okay
3136     break;
3137 
3138   case Qualifiers::OCL_Weak:
3139   case Qualifiers::OCL_Strong:
3140   case Qualifiers::OCL_Autoreleasing:
3141     // FIXME: Can this happen? By this point, ValType should be known
3142     // to be trivially copyable.
3143     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3144       << ValType << Ptr->getSourceRange();
3145     return ExprError();
3146   }
3147 
3148   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
3149   // volatile-ness of the pointee-type inject itself into the result or the
3150   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3151   ValType.removeLocalVolatile();
3152   ValType.removeLocalConst();
3153   QualType ResultType = ValType;
3154   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3155       Form == Init)
3156     ResultType = Context.VoidTy;
3157   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3158     ResultType = Context.BoolTy;
3159 
3160   // The type of a parameter passed 'by value'. In the GNU atomics, such
3161   // arguments are actually passed as pointers.
3162   QualType ByValType = ValType; // 'CP'
3163   if (!IsC11 && !IsN)
3164     ByValType = Ptr->getType();
3165 
3166   // The first argument --- the pointer --- has a fixed type; we
3167   // deduce the types of the rest of the arguments accordingly.  Walk
3168   // the remaining arguments, converting them to the deduced value type.
3169   for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3170     QualType Ty;
3171     if (i < NumVals[Form] + 1) {
3172       switch (i) {
3173       case 1:
3174         // The second argument is the non-atomic operand. For arithmetic, this
3175         // is always passed by value, and for a compare_exchange it is always
3176         // passed by address. For the rest, GNU uses by-address and C11 uses
3177         // by-value.
3178         assert(Form != Load);
3179         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3180           Ty = ValType;
3181         else if (Form == Copy || Form == Xchg)
3182           Ty = ByValType;
3183         else if (Form == Arithmetic)
3184           Ty = Context.getPointerDiffType();
3185         else {
3186           Expr *ValArg = TheCall->getArg(i);
3187           // Treat this argument as _Nonnull as we want to show a warning if
3188           // NULL is passed into it.
3189           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3190           LangAS AS = LangAS::Default;
3191           // Keep address space of non-atomic pointer type.
3192           if (const PointerType *PtrTy =
3193                   ValArg->getType()->getAs<PointerType>()) {
3194             AS = PtrTy->getPointeeType().getAddressSpace();
3195           }
3196           Ty = Context.getPointerType(
3197               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3198         }
3199         break;
3200       case 2:
3201         // The third argument to compare_exchange / GNU exchange is a
3202         // (pointer to a) desired value.
3203         Ty = ByValType;
3204         break;
3205       case 3:
3206         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3207         Ty = Context.BoolTy;
3208         break;
3209       }
3210     } else {
3211       // The order(s) and scope are always converted to int.
3212       Ty = Context.IntTy;
3213     }
3214 
3215     InitializedEntity Entity =
3216         InitializedEntity::InitializeParameter(Context, Ty, false);
3217     ExprResult Arg = TheCall->getArg(i);
3218     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3219     if (Arg.isInvalid())
3220       return true;
3221     TheCall->setArg(i, Arg.get());
3222   }
3223 
3224   // Permute the arguments into a 'consistent' order.
3225   SmallVector<Expr*, 5> SubExprs;
3226   SubExprs.push_back(Ptr);
3227   switch (Form) {
3228   case Init:
3229     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3230     SubExprs.push_back(TheCall->getArg(1)); // Val1
3231     break;
3232   case Load:
3233     SubExprs.push_back(TheCall->getArg(1)); // Order
3234     break;
3235   case LoadCopy:
3236   case Copy:
3237   case Arithmetic:
3238   case Xchg:
3239     SubExprs.push_back(TheCall->getArg(2)); // Order
3240     SubExprs.push_back(TheCall->getArg(1)); // Val1
3241     break;
3242   case GNUXchg:
3243     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3244     SubExprs.push_back(TheCall->getArg(3)); // Order
3245     SubExprs.push_back(TheCall->getArg(1)); // Val1
3246     SubExprs.push_back(TheCall->getArg(2)); // Val2
3247     break;
3248   case C11CmpXchg:
3249     SubExprs.push_back(TheCall->getArg(3)); // Order
3250     SubExprs.push_back(TheCall->getArg(1)); // Val1
3251     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3252     SubExprs.push_back(TheCall->getArg(2)); // Val2
3253     break;
3254   case GNUCmpXchg:
3255     SubExprs.push_back(TheCall->getArg(4)); // Order
3256     SubExprs.push_back(TheCall->getArg(1)); // Val1
3257     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3258     SubExprs.push_back(TheCall->getArg(2)); // Val2
3259     SubExprs.push_back(TheCall->getArg(3)); // Weak
3260     break;
3261   }
3262 
3263   if (SubExprs.size() >= 2 && Form != Init) {
3264     llvm::APSInt Result(32);
3265     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3266         !isValidOrderingForOp(Result.getSExtValue(), Op))
3267       Diag(SubExprs[1]->getLocStart(),
3268            diag::warn_atomic_op_has_invalid_memory_order)
3269           << SubExprs[1]->getSourceRange();
3270   }
3271 
3272   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3273     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3274     llvm::APSInt Result(32);
3275     if (Scope->isIntegerConstantExpr(Result, Context) &&
3276         !ScopeModel->isValid(Result.getZExtValue())) {
3277       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3278           << Scope->getSourceRange();
3279     }
3280     SubExprs.push_back(Scope);
3281   }
3282 
3283   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3284                                             SubExprs, ResultType, Op,
3285                                             TheCall->getRParenLoc());
3286 
3287   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3288        Op == AtomicExpr::AO__c11_atomic_store ||
3289        Op == AtomicExpr::AO__opencl_atomic_load ||
3290        Op == AtomicExpr::AO__opencl_atomic_store ) &&
3291       Context.AtomicUsesUnsupportedLibcall(AE))
3292     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3293         << ((Op == AtomicExpr::AO__c11_atomic_load ||
3294             Op == AtomicExpr::AO__opencl_atomic_load)
3295                 ? 0 : 1);
3296 
3297   return AE;
3298 }
3299 
3300 /// checkBuiltinArgument - Given a call to a builtin function, perform
3301 /// normal type-checking on the given argument, updating the call in
3302 /// place.  This is useful when a builtin function requires custom
3303 /// type-checking for some of its arguments but not necessarily all of
3304 /// them.
3305 ///
3306 /// Returns true on error.
3307 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3308   FunctionDecl *Fn = E->getDirectCallee();
3309   assert(Fn && "builtin call without direct callee!");
3310 
3311   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3312   InitializedEntity Entity =
3313     InitializedEntity::InitializeParameter(S.Context, Param);
3314 
3315   ExprResult Arg = E->getArg(0);
3316   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3317   if (Arg.isInvalid())
3318     return true;
3319 
3320   E->setArg(ArgIndex, Arg.get());
3321   return false;
3322 }
3323 
3324 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3325 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3326 /// type of its first argument.  The main ActOnCallExpr routines have already
3327 /// promoted the types of arguments because all of these calls are prototyped as
3328 /// void(...).
3329 ///
3330 /// This function goes through and does final semantic checking for these
3331 /// builtins,
3332 ExprResult
3333 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3334   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3335   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3336   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3337 
3338   // Ensure that we have at least one argument to do type inference from.
3339   if (TheCall->getNumArgs() < 1) {
3340     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3341       << 0 << 1 << TheCall->getNumArgs()
3342       << TheCall->getCallee()->getSourceRange();
3343     return ExprError();
3344   }
3345 
3346   // Inspect the first argument of the atomic builtin.  This should always be
3347   // a pointer type, whose element is an integral scalar or pointer type.
3348   // Because it is a pointer type, we don't have to worry about any implicit
3349   // casts here.
3350   // FIXME: We don't allow floating point scalars as input.
3351   Expr *FirstArg = TheCall->getArg(0);
3352   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3353   if (FirstArgResult.isInvalid())
3354     return ExprError();
3355   FirstArg = FirstArgResult.get();
3356   TheCall->setArg(0, FirstArg);
3357 
3358   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3359   if (!pointerType) {
3360     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3361       << FirstArg->getType() << FirstArg->getSourceRange();
3362     return ExprError();
3363   }
3364 
3365   QualType ValType = pointerType->getPointeeType();
3366   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3367       !ValType->isBlockPointerType()) {
3368     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3369       << FirstArg->getType() << FirstArg->getSourceRange();
3370     return ExprError();
3371   }
3372 
3373   switch (ValType.getObjCLifetime()) {
3374   case Qualifiers::OCL_None:
3375   case Qualifiers::OCL_ExplicitNone:
3376     // okay
3377     break;
3378 
3379   case Qualifiers::OCL_Weak:
3380   case Qualifiers::OCL_Strong:
3381   case Qualifiers::OCL_Autoreleasing:
3382     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3383       << ValType << FirstArg->getSourceRange();
3384     return ExprError();
3385   }
3386 
3387   // Strip any qualifiers off ValType.
3388   ValType = ValType.getUnqualifiedType();
3389 
3390   // The majority of builtins return a value, but a few have special return
3391   // types, so allow them to override appropriately below.
3392   QualType ResultType = ValType;
3393 
3394   // We need to figure out which concrete builtin this maps onto.  For example,
3395   // __sync_fetch_and_add with a 2 byte object turns into
3396   // __sync_fetch_and_add_2.
3397 #define BUILTIN_ROW(x) \
3398   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3399     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3400 
3401   static const unsigned BuiltinIndices[][5] = {
3402     BUILTIN_ROW(__sync_fetch_and_add),
3403     BUILTIN_ROW(__sync_fetch_and_sub),
3404     BUILTIN_ROW(__sync_fetch_and_or),
3405     BUILTIN_ROW(__sync_fetch_and_and),
3406     BUILTIN_ROW(__sync_fetch_and_xor),
3407     BUILTIN_ROW(__sync_fetch_and_nand),
3408 
3409     BUILTIN_ROW(__sync_add_and_fetch),
3410     BUILTIN_ROW(__sync_sub_and_fetch),
3411     BUILTIN_ROW(__sync_and_and_fetch),
3412     BUILTIN_ROW(__sync_or_and_fetch),
3413     BUILTIN_ROW(__sync_xor_and_fetch),
3414     BUILTIN_ROW(__sync_nand_and_fetch),
3415 
3416     BUILTIN_ROW(__sync_val_compare_and_swap),
3417     BUILTIN_ROW(__sync_bool_compare_and_swap),
3418     BUILTIN_ROW(__sync_lock_test_and_set),
3419     BUILTIN_ROW(__sync_lock_release),
3420     BUILTIN_ROW(__sync_swap)
3421   };
3422 #undef BUILTIN_ROW
3423 
3424   // Determine the index of the size.
3425   unsigned SizeIndex;
3426   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3427   case 1: SizeIndex = 0; break;
3428   case 2: SizeIndex = 1; break;
3429   case 4: SizeIndex = 2; break;
3430   case 8: SizeIndex = 3; break;
3431   case 16: SizeIndex = 4; break;
3432   default:
3433     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3434       << FirstArg->getType() << FirstArg->getSourceRange();
3435     return ExprError();
3436   }
3437 
3438   // Each of these builtins has one pointer argument, followed by some number of
3439   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3440   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3441   // as the number of fixed args.
3442   unsigned BuiltinID = FDecl->getBuiltinID();
3443   unsigned BuiltinIndex, NumFixed = 1;
3444   bool WarnAboutSemanticsChange = false;
3445   switch (BuiltinID) {
3446   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3447   case Builtin::BI__sync_fetch_and_add:
3448   case Builtin::BI__sync_fetch_and_add_1:
3449   case Builtin::BI__sync_fetch_and_add_2:
3450   case Builtin::BI__sync_fetch_and_add_4:
3451   case Builtin::BI__sync_fetch_and_add_8:
3452   case Builtin::BI__sync_fetch_and_add_16:
3453     BuiltinIndex = 0;
3454     break;
3455 
3456   case Builtin::BI__sync_fetch_and_sub:
3457   case Builtin::BI__sync_fetch_and_sub_1:
3458   case Builtin::BI__sync_fetch_and_sub_2:
3459   case Builtin::BI__sync_fetch_and_sub_4:
3460   case Builtin::BI__sync_fetch_and_sub_8:
3461   case Builtin::BI__sync_fetch_and_sub_16:
3462     BuiltinIndex = 1;
3463     break;
3464 
3465   case Builtin::BI__sync_fetch_and_or:
3466   case Builtin::BI__sync_fetch_and_or_1:
3467   case Builtin::BI__sync_fetch_and_or_2:
3468   case Builtin::BI__sync_fetch_and_or_4:
3469   case Builtin::BI__sync_fetch_and_or_8:
3470   case Builtin::BI__sync_fetch_and_or_16:
3471     BuiltinIndex = 2;
3472     break;
3473 
3474   case Builtin::BI__sync_fetch_and_and:
3475   case Builtin::BI__sync_fetch_and_and_1:
3476   case Builtin::BI__sync_fetch_and_and_2:
3477   case Builtin::BI__sync_fetch_and_and_4:
3478   case Builtin::BI__sync_fetch_and_and_8:
3479   case Builtin::BI__sync_fetch_and_and_16:
3480     BuiltinIndex = 3;
3481     break;
3482 
3483   case Builtin::BI__sync_fetch_and_xor:
3484   case Builtin::BI__sync_fetch_and_xor_1:
3485   case Builtin::BI__sync_fetch_and_xor_2:
3486   case Builtin::BI__sync_fetch_and_xor_4:
3487   case Builtin::BI__sync_fetch_and_xor_8:
3488   case Builtin::BI__sync_fetch_and_xor_16:
3489     BuiltinIndex = 4;
3490     break;
3491 
3492   case Builtin::BI__sync_fetch_and_nand:
3493   case Builtin::BI__sync_fetch_and_nand_1:
3494   case Builtin::BI__sync_fetch_and_nand_2:
3495   case Builtin::BI__sync_fetch_and_nand_4:
3496   case Builtin::BI__sync_fetch_and_nand_8:
3497   case Builtin::BI__sync_fetch_and_nand_16:
3498     BuiltinIndex = 5;
3499     WarnAboutSemanticsChange = true;
3500     break;
3501 
3502   case Builtin::BI__sync_add_and_fetch:
3503   case Builtin::BI__sync_add_and_fetch_1:
3504   case Builtin::BI__sync_add_and_fetch_2:
3505   case Builtin::BI__sync_add_and_fetch_4:
3506   case Builtin::BI__sync_add_and_fetch_8:
3507   case Builtin::BI__sync_add_and_fetch_16:
3508     BuiltinIndex = 6;
3509     break;
3510 
3511   case Builtin::BI__sync_sub_and_fetch:
3512   case Builtin::BI__sync_sub_and_fetch_1:
3513   case Builtin::BI__sync_sub_and_fetch_2:
3514   case Builtin::BI__sync_sub_and_fetch_4:
3515   case Builtin::BI__sync_sub_and_fetch_8:
3516   case Builtin::BI__sync_sub_and_fetch_16:
3517     BuiltinIndex = 7;
3518     break;
3519 
3520   case Builtin::BI__sync_and_and_fetch:
3521   case Builtin::BI__sync_and_and_fetch_1:
3522   case Builtin::BI__sync_and_and_fetch_2:
3523   case Builtin::BI__sync_and_and_fetch_4:
3524   case Builtin::BI__sync_and_and_fetch_8:
3525   case Builtin::BI__sync_and_and_fetch_16:
3526     BuiltinIndex = 8;
3527     break;
3528 
3529   case Builtin::BI__sync_or_and_fetch:
3530   case Builtin::BI__sync_or_and_fetch_1:
3531   case Builtin::BI__sync_or_and_fetch_2:
3532   case Builtin::BI__sync_or_and_fetch_4:
3533   case Builtin::BI__sync_or_and_fetch_8:
3534   case Builtin::BI__sync_or_and_fetch_16:
3535     BuiltinIndex = 9;
3536     break;
3537 
3538   case Builtin::BI__sync_xor_and_fetch:
3539   case Builtin::BI__sync_xor_and_fetch_1:
3540   case Builtin::BI__sync_xor_and_fetch_2:
3541   case Builtin::BI__sync_xor_and_fetch_4:
3542   case Builtin::BI__sync_xor_and_fetch_8:
3543   case Builtin::BI__sync_xor_and_fetch_16:
3544     BuiltinIndex = 10;
3545     break;
3546 
3547   case Builtin::BI__sync_nand_and_fetch:
3548   case Builtin::BI__sync_nand_and_fetch_1:
3549   case Builtin::BI__sync_nand_and_fetch_2:
3550   case Builtin::BI__sync_nand_and_fetch_4:
3551   case Builtin::BI__sync_nand_and_fetch_8:
3552   case Builtin::BI__sync_nand_and_fetch_16:
3553     BuiltinIndex = 11;
3554     WarnAboutSemanticsChange = true;
3555     break;
3556 
3557   case Builtin::BI__sync_val_compare_and_swap:
3558   case Builtin::BI__sync_val_compare_and_swap_1:
3559   case Builtin::BI__sync_val_compare_and_swap_2:
3560   case Builtin::BI__sync_val_compare_and_swap_4:
3561   case Builtin::BI__sync_val_compare_and_swap_8:
3562   case Builtin::BI__sync_val_compare_and_swap_16:
3563     BuiltinIndex = 12;
3564     NumFixed = 2;
3565     break;
3566 
3567   case Builtin::BI__sync_bool_compare_and_swap:
3568   case Builtin::BI__sync_bool_compare_and_swap_1:
3569   case Builtin::BI__sync_bool_compare_and_swap_2:
3570   case Builtin::BI__sync_bool_compare_and_swap_4:
3571   case Builtin::BI__sync_bool_compare_and_swap_8:
3572   case Builtin::BI__sync_bool_compare_and_swap_16:
3573     BuiltinIndex = 13;
3574     NumFixed = 2;
3575     ResultType = Context.BoolTy;
3576     break;
3577 
3578   case Builtin::BI__sync_lock_test_and_set:
3579   case Builtin::BI__sync_lock_test_and_set_1:
3580   case Builtin::BI__sync_lock_test_and_set_2:
3581   case Builtin::BI__sync_lock_test_and_set_4:
3582   case Builtin::BI__sync_lock_test_and_set_8:
3583   case Builtin::BI__sync_lock_test_and_set_16:
3584     BuiltinIndex = 14;
3585     break;
3586 
3587   case Builtin::BI__sync_lock_release:
3588   case Builtin::BI__sync_lock_release_1:
3589   case Builtin::BI__sync_lock_release_2:
3590   case Builtin::BI__sync_lock_release_4:
3591   case Builtin::BI__sync_lock_release_8:
3592   case Builtin::BI__sync_lock_release_16:
3593     BuiltinIndex = 15;
3594     NumFixed = 0;
3595     ResultType = Context.VoidTy;
3596     break;
3597 
3598   case Builtin::BI__sync_swap:
3599   case Builtin::BI__sync_swap_1:
3600   case Builtin::BI__sync_swap_2:
3601   case Builtin::BI__sync_swap_4:
3602   case Builtin::BI__sync_swap_8:
3603   case Builtin::BI__sync_swap_16:
3604     BuiltinIndex = 16;
3605     break;
3606   }
3607 
3608   // Now that we know how many fixed arguments we expect, first check that we
3609   // have at least that many.
3610   if (TheCall->getNumArgs() < 1+NumFixed) {
3611     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3612       << 0 << 1+NumFixed << TheCall->getNumArgs()
3613       << TheCall->getCallee()->getSourceRange();
3614     return ExprError();
3615   }
3616 
3617   if (WarnAboutSemanticsChange) {
3618     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3619       << TheCall->getCallee()->getSourceRange();
3620   }
3621 
3622   // Get the decl for the concrete builtin from this, we can tell what the
3623   // concrete integer type we should convert to is.
3624   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3625   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3626   FunctionDecl *NewBuiltinDecl;
3627   if (NewBuiltinID == BuiltinID)
3628     NewBuiltinDecl = FDecl;
3629   else {
3630     // Perform builtin lookup to avoid redeclaring it.
3631     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3632     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3633     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3634     assert(Res.getFoundDecl());
3635     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3636     if (!NewBuiltinDecl)
3637       return ExprError();
3638   }
3639 
3640   // The first argument --- the pointer --- has a fixed type; we
3641   // deduce the types of the rest of the arguments accordingly.  Walk
3642   // the remaining arguments, converting them to the deduced value type.
3643   for (unsigned i = 0; i != NumFixed; ++i) {
3644     ExprResult Arg = TheCall->getArg(i+1);
3645 
3646     // GCC does an implicit conversion to the pointer or integer ValType.  This
3647     // can fail in some cases (1i -> int**), check for this error case now.
3648     // Initialize the argument.
3649     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3650                                                    ValType, /*consume*/ false);
3651     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3652     if (Arg.isInvalid())
3653       return ExprError();
3654 
3655     // Okay, we have something that *can* be converted to the right type.  Check
3656     // to see if there is a potentially weird extension going on here.  This can
3657     // happen when you do an atomic operation on something like an char* and
3658     // pass in 42.  The 42 gets converted to char.  This is even more strange
3659     // for things like 45.123 -> char, etc.
3660     // FIXME: Do this check.
3661     TheCall->setArg(i+1, Arg.get());
3662   }
3663 
3664   ASTContext& Context = this->getASTContext();
3665 
3666   // Create a new DeclRefExpr to refer to the new decl.
3667   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3668       Context,
3669       DRE->getQualifierLoc(),
3670       SourceLocation(),
3671       NewBuiltinDecl,
3672       /*enclosing*/ false,
3673       DRE->getLocation(),
3674       Context.BuiltinFnTy,
3675       DRE->getValueKind());
3676 
3677   // Set the callee in the CallExpr.
3678   // FIXME: This loses syntactic information.
3679   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3680   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3681                                               CK_BuiltinFnToFnPtr);
3682   TheCall->setCallee(PromotedCall.get());
3683 
3684   // Change the result type of the call to match the original value type. This
3685   // is arbitrary, but the codegen for these builtins ins design to handle it
3686   // gracefully.
3687   TheCall->setType(ResultType);
3688 
3689   return TheCallResult;
3690 }
3691 
3692 /// SemaBuiltinNontemporalOverloaded - We have a call to
3693 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3694 /// overloaded function based on the pointer type of its last argument.
3695 ///
3696 /// This function goes through and does final semantic checking for these
3697 /// builtins.
3698 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3699   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3700   DeclRefExpr *DRE =
3701       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3702   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3703   unsigned BuiltinID = FDecl->getBuiltinID();
3704   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3705           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3706          "Unexpected nontemporal load/store builtin!");
3707   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3708   unsigned numArgs = isStore ? 2 : 1;
3709 
3710   // Ensure that we have the proper number of arguments.
3711   if (checkArgCount(*this, TheCall, numArgs))
3712     return ExprError();
3713 
3714   // Inspect the last argument of the nontemporal builtin.  This should always
3715   // be a pointer type, from which we imply the type of the memory access.
3716   // Because it is a pointer type, we don't have to worry about any implicit
3717   // casts here.
3718   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3719   ExprResult PointerArgResult =
3720       DefaultFunctionArrayLvalueConversion(PointerArg);
3721 
3722   if (PointerArgResult.isInvalid())
3723     return ExprError();
3724   PointerArg = PointerArgResult.get();
3725   TheCall->setArg(numArgs - 1, PointerArg);
3726 
3727   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3728   if (!pointerType) {
3729     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3730         << PointerArg->getType() << PointerArg->getSourceRange();
3731     return ExprError();
3732   }
3733 
3734   QualType ValType = pointerType->getPointeeType();
3735 
3736   // Strip any qualifiers off ValType.
3737   ValType = ValType.getUnqualifiedType();
3738   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3739       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3740       !ValType->isVectorType()) {
3741     Diag(DRE->getLocStart(),
3742          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3743         << PointerArg->getType() << PointerArg->getSourceRange();
3744     return ExprError();
3745   }
3746 
3747   if (!isStore) {
3748     TheCall->setType(ValType);
3749     return TheCallResult;
3750   }
3751 
3752   ExprResult ValArg = TheCall->getArg(0);
3753   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3754       Context, ValType, /*consume*/ false);
3755   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3756   if (ValArg.isInvalid())
3757     return ExprError();
3758 
3759   TheCall->setArg(0, ValArg.get());
3760   TheCall->setType(Context.VoidTy);
3761   return TheCallResult;
3762 }
3763 
3764 /// CheckObjCString - Checks that the argument to the builtin
3765 /// CFString constructor is correct
3766 /// Note: It might also make sense to do the UTF-16 conversion here (would
3767 /// simplify the backend).
3768 bool Sema::CheckObjCString(Expr *Arg) {
3769   Arg = Arg->IgnoreParenCasts();
3770   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3771 
3772   if (!Literal || !Literal->isAscii()) {
3773     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3774       << Arg->getSourceRange();
3775     return true;
3776   }
3777 
3778   if (Literal->containsNonAsciiOrNull()) {
3779     StringRef String = Literal->getString();
3780     unsigned NumBytes = String.size();
3781     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3782     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3783     llvm::UTF16 *ToPtr = &ToBuf[0];
3784 
3785     llvm::ConversionResult Result =
3786         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3787                                  ToPtr + NumBytes, llvm::strictConversion);
3788     // Check for conversion failure.
3789     if (Result != llvm::conversionOK)
3790       Diag(Arg->getLocStart(),
3791            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3792   }
3793   return false;
3794 }
3795 
3796 /// CheckObjCString - Checks that the format string argument to the os_log()
3797 /// and os_trace() functions is correct, and converts it to const char *.
3798 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3799   Arg = Arg->IgnoreParenCasts();
3800   auto *Literal = dyn_cast<StringLiteral>(Arg);
3801   if (!Literal) {
3802     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3803       Literal = ObjcLiteral->getString();
3804     }
3805   }
3806 
3807   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3808     return ExprError(
3809         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3810         << Arg->getSourceRange());
3811   }
3812 
3813   ExprResult Result(Literal);
3814   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3815   InitializedEntity Entity =
3816       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3817   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3818   return Result;
3819 }
3820 
3821 /// Check that the user is calling the appropriate va_start builtin for the
3822 /// target and calling convention.
3823 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3824   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3825   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3826   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3827   bool IsWindows = TT.isOSWindows();
3828   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3829   if (IsX64 || IsAArch64) {
3830     CallingConv CC = CC_C;
3831     if (const FunctionDecl *FD = S.getCurFunctionDecl())
3832       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3833     if (IsMSVAStart) {
3834       // Don't allow this in System V ABI functions.
3835       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3836         return S.Diag(Fn->getLocStart(),
3837                       diag::err_ms_va_start_used_in_sysv_function);
3838     } else {
3839       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3840       // On x64 Windows, don't allow this in System V ABI functions.
3841       // (Yes, that means there's no corresponding way to support variadic
3842       // System V ABI functions on Windows.)
3843       if ((IsWindows && CC == CC_X86_64SysV) ||
3844           (!IsWindows && CC == CC_Win64))
3845         return S.Diag(Fn->getLocStart(),
3846                       diag::err_va_start_used_in_wrong_abi_function)
3847                << !IsWindows;
3848     }
3849     return false;
3850   }
3851 
3852   if (IsMSVAStart)
3853     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3854   return false;
3855 }
3856 
3857 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3858                                              ParmVarDecl **LastParam = nullptr) {
3859   // Determine whether the current function, block, or obj-c method is variadic
3860   // and get its parameter list.
3861   bool IsVariadic = false;
3862   ArrayRef<ParmVarDecl *> Params;
3863   DeclContext *Caller = S.CurContext;
3864   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3865     IsVariadic = Block->isVariadic();
3866     Params = Block->parameters();
3867   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3868     IsVariadic = FD->isVariadic();
3869     Params = FD->parameters();
3870   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3871     IsVariadic = MD->isVariadic();
3872     // FIXME: This isn't correct for methods (results in bogus warning).
3873     Params = MD->parameters();
3874   } else if (isa<CapturedDecl>(Caller)) {
3875     // We don't support va_start in a CapturedDecl.
3876     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3877     return true;
3878   } else {
3879     // This must be some other declcontext that parses exprs.
3880     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3881     return true;
3882   }
3883 
3884   if (!IsVariadic) {
3885     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3886     return true;
3887   }
3888 
3889   if (LastParam)
3890     *LastParam = Params.empty() ? nullptr : Params.back();
3891 
3892   return false;
3893 }
3894 
3895 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3896 /// for validity.  Emit an error and return true on failure; return false
3897 /// on success.
3898 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3899   Expr *Fn = TheCall->getCallee();
3900 
3901   if (checkVAStartABI(*this, BuiltinID, Fn))
3902     return true;
3903 
3904   if (TheCall->getNumArgs() > 2) {
3905     Diag(TheCall->getArg(2)->getLocStart(),
3906          diag::err_typecheck_call_too_many_args)
3907       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3908       << Fn->getSourceRange()
3909       << SourceRange(TheCall->getArg(2)->getLocStart(),
3910                      (*(TheCall->arg_end()-1))->getLocEnd());
3911     return true;
3912   }
3913 
3914   if (TheCall->getNumArgs() < 2) {
3915     return Diag(TheCall->getLocEnd(),
3916       diag::err_typecheck_call_too_few_args_at_least)
3917       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3918   }
3919 
3920   // Type-check the first argument normally.
3921   if (checkBuiltinArgument(*this, TheCall, 0))
3922     return true;
3923 
3924   // Check that the current function is variadic, and get its last parameter.
3925   ParmVarDecl *LastParam;
3926   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3927     return true;
3928 
3929   // Verify that the second argument to the builtin is the last argument of the
3930   // current function or method.
3931   bool SecondArgIsLastNamedArgument = false;
3932   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3933 
3934   // These are valid if SecondArgIsLastNamedArgument is false after the next
3935   // block.
3936   QualType Type;
3937   SourceLocation ParamLoc;
3938   bool IsCRegister = false;
3939 
3940   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3941     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3942       SecondArgIsLastNamedArgument = PV == LastParam;
3943 
3944       Type = PV->getType();
3945       ParamLoc = PV->getLocation();
3946       IsCRegister =
3947           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3948     }
3949   }
3950 
3951   if (!SecondArgIsLastNamedArgument)
3952     Diag(TheCall->getArg(1)->getLocStart(),
3953          diag::warn_second_arg_of_va_start_not_last_named_param);
3954   else if (IsCRegister || Type->isReferenceType() ||
3955            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3956              // Promotable integers are UB, but enumerations need a bit of
3957              // extra checking to see what their promotable type actually is.
3958              if (!Type->isPromotableIntegerType())
3959                return false;
3960              if (!Type->isEnumeralType())
3961                return true;
3962              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3963              return !(ED &&
3964                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3965            }()) {
3966     unsigned Reason = 0;
3967     if (Type->isReferenceType())  Reason = 1;
3968     else if (IsCRegister)         Reason = 2;
3969     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3970     Diag(ParamLoc, diag::note_parameter_type) << Type;
3971   }
3972 
3973   TheCall->setType(Context.VoidTy);
3974   return false;
3975 }
3976 
3977 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
3978   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3979   //                 const char *named_addr);
3980 
3981   Expr *Func = Call->getCallee();
3982 
3983   if (Call->getNumArgs() < 3)
3984     return Diag(Call->getLocEnd(),
3985                 diag::err_typecheck_call_too_few_args_at_least)
3986            << 0 /*function call*/ << 3 << Call->getNumArgs();
3987 
3988   // Type-check the first argument normally.
3989   if (checkBuiltinArgument(*this, Call, 0))
3990     return true;
3991 
3992   // Check that the current function is variadic.
3993   if (checkVAStartIsInVariadicFunction(*this, Func))
3994     return true;
3995 
3996   // __va_start on Windows does not validate the parameter qualifiers
3997 
3998   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
3999   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4000 
4001   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4002   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4003 
4004   const QualType &ConstCharPtrTy =
4005       Context.getPointerType(Context.CharTy.withConst());
4006   if (!Arg1Ty->isPointerType() ||
4007       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4008     Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4009         << Arg1->getType() << ConstCharPtrTy
4010         << 1 /* different class */
4011         << 0 /* qualifier difference */
4012         << 3 /* parameter mismatch */
4013         << 2 << Arg1->getType() << ConstCharPtrTy;
4014 
4015   const QualType SizeTy = Context.getSizeType();
4016   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4017     Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4018         << Arg2->getType() << SizeTy
4019         << 1 /* different class */
4020         << 0 /* qualifier difference */
4021         << 3 /* parameter mismatch */
4022         << 3 << Arg2->getType() << SizeTy;
4023 
4024   return false;
4025 }
4026 
4027 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4028 /// friends.  This is declared to take (...), so we have to check everything.
4029 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4030   if (TheCall->getNumArgs() < 2)
4031     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4032       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4033   if (TheCall->getNumArgs() > 2)
4034     return Diag(TheCall->getArg(2)->getLocStart(),
4035                 diag::err_typecheck_call_too_many_args)
4036       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4037       << SourceRange(TheCall->getArg(2)->getLocStart(),
4038                      (*(TheCall->arg_end()-1))->getLocEnd());
4039 
4040   ExprResult OrigArg0 = TheCall->getArg(0);
4041   ExprResult OrigArg1 = TheCall->getArg(1);
4042 
4043   // Do standard promotions between the two arguments, returning their common
4044   // type.
4045   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4046   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4047     return true;
4048 
4049   // Make sure any conversions are pushed back into the call; this is
4050   // type safe since unordered compare builtins are declared as "_Bool
4051   // foo(...)".
4052   TheCall->setArg(0, OrigArg0.get());
4053   TheCall->setArg(1, OrigArg1.get());
4054 
4055   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4056     return false;
4057 
4058   // If the common type isn't a real floating type, then the arguments were
4059   // invalid for this operation.
4060   if (Res.isNull() || !Res->isRealFloatingType())
4061     return Diag(OrigArg0.get()->getLocStart(),
4062                 diag::err_typecheck_call_invalid_ordered_compare)
4063       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4064       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4065 
4066   return false;
4067 }
4068 
4069 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4070 /// __builtin_isnan and friends.  This is declared to take (...), so we have
4071 /// to check everything. We expect the last argument to be a floating point
4072 /// value.
4073 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4074   if (TheCall->getNumArgs() < NumArgs)
4075     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4076       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4077   if (TheCall->getNumArgs() > NumArgs)
4078     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4079                 diag::err_typecheck_call_too_many_args)
4080       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4081       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4082                      (*(TheCall->arg_end()-1))->getLocEnd());
4083 
4084   Expr *OrigArg = TheCall->getArg(NumArgs-1);
4085 
4086   if (OrigArg->isTypeDependent())
4087     return false;
4088 
4089   // This operation requires a non-_Complex floating-point number.
4090   if (!OrigArg->getType()->isRealFloatingType())
4091     return Diag(OrigArg->getLocStart(),
4092                 diag::err_typecheck_call_invalid_unary_fp)
4093       << OrigArg->getType() << OrigArg->getSourceRange();
4094 
4095   // If this is an implicit conversion from float -> float or double, remove it.
4096   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4097     // Only remove standard FloatCasts, leaving other casts inplace
4098     if (Cast->getCastKind() == CK_FloatingCast) {
4099       Expr *CastArg = Cast->getSubExpr();
4100       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4101           assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4102                   Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4103                "promotion from float to either float or double is the only expected cast here");
4104         Cast->setSubExpr(nullptr);
4105         TheCall->setArg(NumArgs-1, CastArg);
4106       }
4107     }
4108   }
4109 
4110   return false;
4111 }
4112 
4113 // Customized Sema Checking for VSX builtins that have the following signature:
4114 // vector [...] builtinName(vector [...], vector [...], const int);
4115 // Which takes the same type of vectors (any legal vector type) for the first
4116 // two arguments and takes compile time constant for the third argument.
4117 // Example builtins are :
4118 // vector double vec_xxpermdi(vector double, vector double, int);
4119 // vector short vec_xxsldwi(vector short, vector short, int);
4120 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4121   unsigned ExpectedNumArgs = 3;
4122   if (TheCall->getNumArgs() < ExpectedNumArgs)
4123     return Diag(TheCall->getLocEnd(),
4124                 diag::err_typecheck_call_too_few_args_at_least)
4125            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
4126            << TheCall->getSourceRange();
4127 
4128   if (TheCall->getNumArgs() > ExpectedNumArgs)
4129     return Diag(TheCall->getLocEnd(),
4130                 diag::err_typecheck_call_too_many_args_at_most)
4131            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4132            << TheCall->getSourceRange();
4133 
4134   // Check the third argument is a compile time constant
4135   llvm::APSInt Value;
4136   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4137     return Diag(TheCall->getLocStart(),
4138                 diag::err_vsx_builtin_nonconstant_argument)
4139            << 3 /* argument index */ << TheCall->getDirectCallee()
4140            << SourceRange(TheCall->getArg(2)->getLocStart(),
4141                           TheCall->getArg(2)->getLocEnd());
4142 
4143   QualType Arg1Ty = TheCall->getArg(0)->getType();
4144   QualType Arg2Ty = TheCall->getArg(1)->getType();
4145 
4146   // Check the type of argument 1 and argument 2 are vectors.
4147   SourceLocation BuiltinLoc = TheCall->getLocStart();
4148   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4149       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4150     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4151            << TheCall->getDirectCallee()
4152            << SourceRange(TheCall->getArg(0)->getLocStart(),
4153                           TheCall->getArg(1)->getLocEnd());
4154   }
4155 
4156   // Check the first two arguments are the same type.
4157   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4158     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4159            << TheCall->getDirectCallee()
4160            << SourceRange(TheCall->getArg(0)->getLocStart(),
4161                           TheCall->getArg(1)->getLocEnd());
4162   }
4163 
4164   // When default clang type checking is turned off and the customized type
4165   // checking is used, the returning type of the function must be explicitly
4166   // set. Otherwise it is _Bool by default.
4167   TheCall->setType(Arg1Ty);
4168 
4169   return false;
4170 }
4171 
4172 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4173 // This is declared to take (...), so we have to check everything.
4174 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4175   if (TheCall->getNumArgs() < 2)
4176     return ExprError(Diag(TheCall->getLocEnd(),
4177                           diag::err_typecheck_call_too_few_args_at_least)
4178                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4179                      << TheCall->getSourceRange());
4180 
4181   // Determine which of the following types of shufflevector we're checking:
4182   // 1) unary, vector mask: (lhs, mask)
4183   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4184   QualType resType = TheCall->getArg(0)->getType();
4185   unsigned numElements = 0;
4186 
4187   if (!TheCall->getArg(0)->isTypeDependent() &&
4188       !TheCall->getArg(1)->isTypeDependent()) {
4189     QualType LHSType = TheCall->getArg(0)->getType();
4190     QualType RHSType = TheCall->getArg(1)->getType();
4191 
4192     if (!LHSType->isVectorType() || !RHSType->isVectorType())
4193       return ExprError(Diag(TheCall->getLocStart(),
4194                             diag::err_vec_builtin_non_vector)
4195                        << TheCall->getDirectCallee()
4196                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4197                                       TheCall->getArg(1)->getLocEnd()));
4198 
4199     numElements = LHSType->getAs<VectorType>()->getNumElements();
4200     unsigned numResElements = TheCall->getNumArgs() - 2;
4201 
4202     // Check to see if we have a call with 2 vector arguments, the unary shuffle
4203     // with mask.  If so, verify that RHS is an integer vector type with the
4204     // same number of elts as lhs.
4205     if (TheCall->getNumArgs() == 2) {
4206       if (!RHSType->hasIntegerRepresentation() ||
4207           RHSType->getAs<VectorType>()->getNumElements() != numElements)
4208         return ExprError(Diag(TheCall->getLocStart(),
4209                               diag::err_vec_builtin_incompatible_vector)
4210                          << TheCall->getDirectCallee()
4211                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4212                                         TheCall->getArg(1)->getLocEnd()));
4213     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4214       return ExprError(Diag(TheCall->getLocStart(),
4215                             diag::err_vec_builtin_incompatible_vector)
4216                        << TheCall->getDirectCallee()
4217                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4218                                       TheCall->getArg(1)->getLocEnd()));
4219     } else if (numElements != numResElements) {
4220       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4221       resType = Context.getVectorType(eltType, numResElements,
4222                                       VectorType::GenericVector);
4223     }
4224   }
4225 
4226   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4227     if (TheCall->getArg(i)->isTypeDependent() ||
4228         TheCall->getArg(i)->isValueDependent())
4229       continue;
4230 
4231     llvm::APSInt Result(32);
4232     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4233       return ExprError(Diag(TheCall->getLocStart(),
4234                             diag::err_shufflevector_nonconstant_argument)
4235                        << TheCall->getArg(i)->getSourceRange());
4236 
4237     // Allow -1 which will be translated to undef in the IR.
4238     if (Result.isSigned() && Result.isAllOnesValue())
4239       continue;
4240 
4241     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4242       return ExprError(Diag(TheCall->getLocStart(),
4243                             diag::err_shufflevector_argument_too_large)
4244                        << TheCall->getArg(i)->getSourceRange());
4245   }
4246 
4247   SmallVector<Expr*, 32> exprs;
4248 
4249   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4250     exprs.push_back(TheCall->getArg(i));
4251     TheCall->setArg(i, nullptr);
4252   }
4253 
4254   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4255                                          TheCall->getCallee()->getLocStart(),
4256                                          TheCall->getRParenLoc());
4257 }
4258 
4259 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4260 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4261                                        SourceLocation BuiltinLoc,
4262                                        SourceLocation RParenLoc) {
4263   ExprValueKind VK = VK_RValue;
4264   ExprObjectKind OK = OK_Ordinary;
4265   QualType DstTy = TInfo->getType();
4266   QualType SrcTy = E->getType();
4267 
4268   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4269     return ExprError(Diag(BuiltinLoc,
4270                           diag::err_convertvector_non_vector)
4271                      << E->getSourceRange());
4272   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4273     return ExprError(Diag(BuiltinLoc,
4274                           diag::err_convertvector_non_vector_type));
4275 
4276   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4277     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4278     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4279     if (SrcElts != DstElts)
4280       return ExprError(Diag(BuiltinLoc,
4281                             diag::err_convertvector_incompatible_vector)
4282                        << E->getSourceRange());
4283   }
4284 
4285   return new (Context)
4286       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4287 }
4288 
4289 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4290 // This is declared to take (const void*, ...) and can take two
4291 // optional constant int args.
4292 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4293   unsigned NumArgs = TheCall->getNumArgs();
4294 
4295   if (NumArgs > 3)
4296     return Diag(TheCall->getLocEnd(),
4297              diag::err_typecheck_call_too_many_args_at_most)
4298              << 0 /*function call*/ << 3 << NumArgs
4299              << TheCall->getSourceRange();
4300 
4301   // Argument 0 is checked for us and the remaining arguments must be
4302   // constant integers.
4303   for (unsigned i = 1; i != NumArgs; ++i)
4304     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4305       return true;
4306 
4307   return false;
4308 }
4309 
4310 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4311 // __assume does not evaluate its arguments, and should warn if its argument
4312 // has side effects.
4313 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4314   Expr *Arg = TheCall->getArg(0);
4315   if (Arg->isInstantiationDependent()) return false;
4316 
4317   if (Arg->HasSideEffects(Context))
4318     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4319       << Arg->getSourceRange()
4320       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4321 
4322   return false;
4323 }
4324 
4325 /// Handle __builtin_alloca_with_align. This is declared
4326 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4327 /// than 8.
4328 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4329   // The alignment must be a constant integer.
4330   Expr *Arg = TheCall->getArg(1);
4331 
4332   // We can't check the value of a dependent argument.
4333   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4334     if (const auto *UE =
4335             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4336       if (UE->getKind() == UETT_AlignOf)
4337         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4338           << Arg->getSourceRange();
4339 
4340     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4341 
4342     if (!Result.isPowerOf2())
4343       return Diag(TheCall->getLocStart(),
4344                   diag::err_alignment_not_power_of_two)
4345            << Arg->getSourceRange();
4346 
4347     if (Result < Context.getCharWidth())
4348       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4349            << (unsigned)Context.getCharWidth()
4350            << Arg->getSourceRange();
4351 
4352     if (Result > std::numeric_limits<int32_t>::max())
4353       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4354            << std::numeric_limits<int32_t>::max()
4355            << Arg->getSourceRange();
4356   }
4357 
4358   return false;
4359 }
4360 
4361 /// Handle __builtin_assume_aligned. This is declared
4362 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4363 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4364   unsigned NumArgs = TheCall->getNumArgs();
4365 
4366   if (NumArgs > 3)
4367     return Diag(TheCall->getLocEnd(),
4368              diag::err_typecheck_call_too_many_args_at_most)
4369              << 0 /*function call*/ << 3 << NumArgs
4370              << TheCall->getSourceRange();
4371 
4372   // The alignment must be a constant integer.
4373   Expr *Arg = TheCall->getArg(1);
4374 
4375   // We can't check the value of a dependent argument.
4376   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4377     llvm::APSInt Result;
4378     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4379       return true;
4380 
4381     if (!Result.isPowerOf2())
4382       return Diag(TheCall->getLocStart(),
4383                   diag::err_alignment_not_power_of_two)
4384            << Arg->getSourceRange();
4385   }
4386 
4387   if (NumArgs > 2) {
4388     ExprResult Arg(TheCall->getArg(2));
4389     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4390       Context.getSizeType(), false);
4391     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4392     if (Arg.isInvalid()) return true;
4393     TheCall->setArg(2, Arg.get());
4394   }
4395 
4396   return false;
4397 }
4398 
4399 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4400   unsigned BuiltinID =
4401       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4402   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4403 
4404   unsigned NumArgs = TheCall->getNumArgs();
4405   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4406   if (NumArgs < NumRequiredArgs) {
4407     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4408            << 0 /* function call */ << NumRequiredArgs << NumArgs
4409            << TheCall->getSourceRange();
4410   }
4411   if (NumArgs >= NumRequiredArgs + 0x100) {
4412     return Diag(TheCall->getLocEnd(),
4413                 diag::err_typecheck_call_too_many_args_at_most)
4414            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4415            << TheCall->getSourceRange();
4416   }
4417   unsigned i = 0;
4418 
4419   // For formatting call, check buffer arg.
4420   if (!IsSizeCall) {
4421     ExprResult Arg(TheCall->getArg(i));
4422     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4423         Context, Context.VoidPtrTy, false);
4424     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4425     if (Arg.isInvalid())
4426       return true;
4427     TheCall->setArg(i, Arg.get());
4428     i++;
4429   }
4430 
4431   // Check string literal arg.
4432   unsigned FormatIdx = i;
4433   {
4434     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4435     if (Arg.isInvalid())
4436       return true;
4437     TheCall->setArg(i, Arg.get());
4438     i++;
4439   }
4440 
4441   // Make sure variadic args are scalar.
4442   unsigned FirstDataArg = i;
4443   while (i < NumArgs) {
4444     ExprResult Arg = DefaultVariadicArgumentPromotion(
4445         TheCall->getArg(i), VariadicFunction, nullptr);
4446     if (Arg.isInvalid())
4447       return true;
4448     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4449     if (ArgSize.getQuantity() >= 0x100) {
4450       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4451              << i << (int)ArgSize.getQuantity() << 0xff
4452              << TheCall->getSourceRange();
4453     }
4454     TheCall->setArg(i, Arg.get());
4455     i++;
4456   }
4457 
4458   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4459   // call to avoid duplicate diagnostics.
4460   if (!IsSizeCall) {
4461     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4462     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4463     bool Success = CheckFormatArguments(
4464         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4465         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4466         CheckedVarArgs);
4467     if (!Success)
4468       return true;
4469   }
4470 
4471   if (IsSizeCall) {
4472     TheCall->setType(Context.getSizeType());
4473   } else {
4474     TheCall->setType(Context.VoidPtrTy);
4475   }
4476   return false;
4477 }
4478 
4479 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4480 /// TheCall is a constant expression.
4481 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4482                                   llvm::APSInt &Result) {
4483   Expr *Arg = TheCall->getArg(ArgNum);
4484   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4485   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4486 
4487   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4488 
4489   if (!Arg->isIntegerConstantExpr(Result, Context))
4490     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4491                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4492 
4493   return false;
4494 }
4495 
4496 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4497 /// TheCall is a constant expression in the range [Low, High].
4498 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4499                                        int Low, int High) {
4500   llvm::APSInt Result;
4501 
4502   // We can't check the value of a dependent argument.
4503   Expr *Arg = TheCall->getArg(ArgNum);
4504   if (Arg->isTypeDependent() || Arg->isValueDependent())
4505     return false;
4506 
4507   // Check constant-ness first.
4508   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4509     return true;
4510 
4511   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4512     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4513       << Low << High << Arg->getSourceRange();
4514 
4515   return false;
4516 }
4517 
4518 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4519 /// TheCall is a constant expression is a multiple of Num..
4520 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4521                                           unsigned Num) {
4522   llvm::APSInt Result;
4523 
4524   // We can't check the value of a dependent argument.
4525   Expr *Arg = TheCall->getArg(ArgNum);
4526   if (Arg->isTypeDependent() || Arg->isValueDependent())
4527     return false;
4528 
4529   // Check constant-ness first.
4530   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4531     return true;
4532 
4533   if (Result.getSExtValue() % Num != 0)
4534     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4535       << Num << Arg->getSourceRange();
4536 
4537   return false;
4538 }
4539 
4540 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4541 /// TheCall is an ARM/AArch64 special register string literal.
4542 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4543                                     int ArgNum, unsigned ExpectedFieldNum,
4544                                     bool AllowName) {
4545   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4546                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4547                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4548                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4549                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4550                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4551   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4552                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4553                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4554                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4555                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4556                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4557   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4558 
4559   // We can't check the value of a dependent argument.
4560   Expr *Arg = TheCall->getArg(ArgNum);
4561   if (Arg->isTypeDependent() || Arg->isValueDependent())
4562     return false;
4563 
4564   // Check if the argument is a string literal.
4565   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4566     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4567            << Arg->getSourceRange();
4568 
4569   // Check the type of special register given.
4570   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4571   SmallVector<StringRef, 6> Fields;
4572   Reg.split(Fields, ":");
4573 
4574   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4575     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4576            << Arg->getSourceRange();
4577 
4578   // If the string is the name of a register then we cannot check that it is
4579   // valid here but if the string is of one the forms described in ACLE then we
4580   // can check that the supplied fields are integers and within the valid
4581   // ranges.
4582   if (Fields.size() > 1) {
4583     bool FiveFields = Fields.size() == 5;
4584 
4585     bool ValidString = true;
4586     if (IsARMBuiltin) {
4587       ValidString &= Fields[0].startswith_lower("cp") ||
4588                      Fields[0].startswith_lower("p");
4589       if (ValidString)
4590         Fields[0] =
4591           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4592 
4593       ValidString &= Fields[2].startswith_lower("c");
4594       if (ValidString)
4595         Fields[2] = Fields[2].drop_front(1);
4596 
4597       if (FiveFields) {
4598         ValidString &= Fields[3].startswith_lower("c");
4599         if (ValidString)
4600           Fields[3] = Fields[3].drop_front(1);
4601       }
4602     }
4603 
4604     SmallVector<int, 5> Ranges;
4605     if (FiveFields)
4606       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4607     else
4608       Ranges.append({15, 7, 15});
4609 
4610     for (unsigned i=0; i<Fields.size(); ++i) {
4611       int IntField;
4612       ValidString &= !Fields[i].getAsInteger(10, IntField);
4613       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4614     }
4615 
4616     if (!ValidString)
4617       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4618              << Arg->getSourceRange();
4619   } else if (IsAArch64Builtin && Fields.size() == 1) {
4620     // If the register name is one of those that appear in the condition below
4621     // and the special register builtin being used is one of the write builtins,
4622     // then we require that the argument provided for writing to the register
4623     // is an integer constant expression. This is because it will be lowered to
4624     // an MSR (immediate) instruction, so we need to know the immediate at
4625     // compile time.
4626     if (TheCall->getNumArgs() != 2)
4627       return false;
4628 
4629     std::string RegLower = Reg.lower();
4630     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4631         RegLower != "pan" && RegLower != "uao")
4632       return false;
4633 
4634     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4635   }
4636 
4637   return false;
4638 }
4639 
4640 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4641 /// This checks that the target supports __builtin_longjmp and
4642 /// that val is a constant 1.
4643 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4644   if (!Context.getTargetInfo().hasSjLjLowering())
4645     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4646              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4647 
4648   Expr *Arg = TheCall->getArg(1);
4649   llvm::APSInt Result;
4650 
4651   // TODO: This is less than ideal. Overload this to take a value.
4652   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4653     return true;
4654 
4655   if (Result != 1)
4656     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4657              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4658 
4659   return false;
4660 }
4661 
4662 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4663 /// This checks that the target supports __builtin_setjmp.
4664 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4665   if (!Context.getTargetInfo().hasSjLjLowering())
4666     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4667              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4668   return false;
4669 }
4670 
4671 namespace {
4672 
4673 class UncoveredArgHandler {
4674   enum { Unknown = -1, AllCovered = -2 };
4675 
4676   signed FirstUncoveredArg = Unknown;
4677   SmallVector<const Expr *, 4> DiagnosticExprs;
4678 
4679 public:
4680   UncoveredArgHandler() = default;
4681 
4682   bool hasUncoveredArg() const {
4683     return (FirstUncoveredArg >= 0);
4684   }
4685 
4686   unsigned getUncoveredArg() const {
4687     assert(hasUncoveredArg() && "no uncovered argument");
4688     return FirstUncoveredArg;
4689   }
4690 
4691   void setAllCovered() {
4692     // A string has been found with all arguments covered, so clear out
4693     // the diagnostics.
4694     DiagnosticExprs.clear();
4695     FirstUncoveredArg = AllCovered;
4696   }
4697 
4698   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4699     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4700 
4701     // Don't update if a previous string covers all arguments.
4702     if (FirstUncoveredArg == AllCovered)
4703       return;
4704 
4705     // UncoveredArgHandler tracks the highest uncovered argument index
4706     // and with it all the strings that match this index.
4707     if (NewFirstUncoveredArg == FirstUncoveredArg)
4708       DiagnosticExprs.push_back(StrExpr);
4709     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4710       DiagnosticExprs.clear();
4711       DiagnosticExprs.push_back(StrExpr);
4712       FirstUncoveredArg = NewFirstUncoveredArg;
4713     }
4714   }
4715 
4716   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4717 };
4718 
4719 enum StringLiteralCheckType {
4720   SLCT_NotALiteral,
4721   SLCT_UncheckedLiteral,
4722   SLCT_CheckedLiteral
4723 };
4724 
4725 } // namespace
4726 
4727 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4728                                      BinaryOperatorKind BinOpKind,
4729                                      bool AddendIsRight) {
4730   unsigned BitWidth = Offset.getBitWidth();
4731   unsigned AddendBitWidth = Addend.getBitWidth();
4732   // There might be negative interim results.
4733   if (Addend.isUnsigned()) {
4734     Addend = Addend.zext(++AddendBitWidth);
4735     Addend.setIsSigned(true);
4736   }
4737   // Adjust the bit width of the APSInts.
4738   if (AddendBitWidth > BitWidth) {
4739     Offset = Offset.sext(AddendBitWidth);
4740     BitWidth = AddendBitWidth;
4741   } else if (BitWidth > AddendBitWidth) {
4742     Addend = Addend.sext(BitWidth);
4743   }
4744 
4745   bool Ov = false;
4746   llvm::APSInt ResOffset = Offset;
4747   if (BinOpKind == BO_Add)
4748     ResOffset = Offset.sadd_ov(Addend, Ov);
4749   else {
4750     assert(AddendIsRight && BinOpKind == BO_Sub &&
4751            "operator must be add or sub with addend on the right");
4752     ResOffset = Offset.ssub_ov(Addend, Ov);
4753   }
4754 
4755   // We add an offset to a pointer here so we should support an offset as big as
4756   // possible.
4757   if (Ov) {
4758     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4759            "index (intermediate) result too big");
4760     Offset = Offset.sext(2 * BitWidth);
4761     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4762     return;
4763   }
4764 
4765   Offset = ResOffset;
4766 }
4767 
4768 namespace {
4769 
4770 // This is a wrapper class around StringLiteral to support offsetted string
4771 // literals as format strings. It takes the offset into account when returning
4772 // the string and its length or the source locations to display notes correctly.
4773 class FormatStringLiteral {
4774   const StringLiteral *FExpr;
4775   int64_t Offset;
4776 
4777  public:
4778   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4779       : FExpr(fexpr), Offset(Offset) {}
4780 
4781   StringRef getString() const {
4782     return FExpr->getString().drop_front(Offset);
4783   }
4784 
4785   unsigned getByteLength() const {
4786     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4787   }
4788 
4789   unsigned getLength() const { return FExpr->getLength() - Offset; }
4790   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4791 
4792   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4793 
4794   QualType getType() const { return FExpr->getType(); }
4795 
4796   bool isAscii() const { return FExpr->isAscii(); }
4797   bool isWide() const { return FExpr->isWide(); }
4798   bool isUTF8() const { return FExpr->isUTF8(); }
4799   bool isUTF16() const { return FExpr->isUTF16(); }
4800   bool isUTF32() const { return FExpr->isUTF32(); }
4801   bool isPascal() const { return FExpr->isPascal(); }
4802 
4803   SourceLocation getLocationOfByte(
4804       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4805       const TargetInfo &Target, unsigned *StartToken = nullptr,
4806       unsigned *StartTokenByteOffset = nullptr) const {
4807     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4808                                     StartToken, StartTokenByteOffset);
4809   }
4810 
4811   SourceLocation getLocStart() const LLVM_READONLY {
4812     return FExpr->getLocStart().getLocWithOffset(Offset);
4813   }
4814 
4815   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4816 };
4817 
4818 }  // namespace
4819 
4820 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4821                               const Expr *OrigFormatExpr,
4822                               ArrayRef<const Expr *> Args,
4823                               bool HasVAListArg, unsigned format_idx,
4824                               unsigned firstDataArg,
4825                               Sema::FormatStringType Type,
4826                               bool inFunctionCall,
4827                               Sema::VariadicCallType CallType,
4828                               llvm::SmallBitVector &CheckedVarArgs,
4829                               UncoveredArgHandler &UncoveredArg);
4830 
4831 // Determine if an expression is a string literal or constant string.
4832 // If this function returns false on the arguments to a function expecting a
4833 // format string, we will usually need to emit a warning.
4834 // True string literals are then checked by CheckFormatString.
4835 static StringLiteralCheckType
4836 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4837                       bool HasVAListArg, unsigned format_idx,
4838                       unsigned firstDataArg, Sema::FormatStringType Type,
4839                       Sema::VariadicCallType CallType, bool InFunctionCall,
4840                       llvm::SmallBitVector &CheckedVarArgs,
4841                       UncoveredArgHandler &UncoveredArg,
4842                       llvm::APSInt Offset) {
4843  tryAgain:
4844   assert(Offset.isSigned() && "invalid offset");
4845 
4846   if (E->isTypeDependent() || E->isValueDependent())
4847     return SLCT_NotALiteral;
4848 
4849   E = E->IgnoreParenCasts();
4850 
4851   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4852     // Technically -Wformat-nonliteral does not warn about this case.
4853     // The behavior of printf and friends in this case is implementation
4854     // dependent.  Ideally if the format string cannot be null then
4855     // it should have a 'nonnull' attribute in the function prototype.
4856     return SLCT_UncheckedLiteral;
4857 
4858   switch (E->getStmtClass()) {
4859   case Stmt::BinaryConditionalOperatorClass:
4860   case Stmt::ConditionalOperatorClass: {
4861     // The expression is a literal if both sub-expressions were, and it was
4862     // completely checked only if both sub-expressions were checked.
4863     const AbstractConditionalOperator *C =
4864         cast<AbstractConditionalOperator>(E);
4865 
4866     // Determine whether it is necessary to check both sub-expressions, for
4867     // example, because the condition expression is a constant that can be
4868     // evaluated at compile time.
4869     bool CheckLeft = true, CheckRight = true;
4870 
4871     bool Cond;
4872     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4873       if (Cond)
4874         CheckRight = false;
4875       else
4876         CheckLeft = false;
4877     }
4878 
4879     // We need to maintain the offsets for the right and the left hand side
4880     // separately to check if every possible indexed expression is a valid
4881     // string literal. They might have different offsets for different string
4882     // literals in the end.
4883     StringLiteralCheckType Left;
4884     if (!CheckLeft)
4885       Left = SLCT_UncheckedLiteral;
4886     else {
4887       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4888                                    HasVAListArg, format_idx, firstDataArg,
4889                                    Type, CallType, InFunctionCall,
4890                                    CheckedVarArgs, UncoveredArg, Offset);
4891       if (Left == SLCT_NotALiteral || !CheckRight) {
4892         return Left;
4893       }
4894     }
4895 
4896     StringLiteralCheckType Right =
4897         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4898                               HasVAListArg, format_idx, firstDataArg,
4899                               Type, CallType, InFunctionCall, CheckedVarArgs,
4900                               UncoveredArg, Offset);
4901 
4902     return (CheckLeft && Left < Right) ? Left : Right;
4903   }
4904 
4905   case Stmt::ImplicitCastExprClass:
4906     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4907     goto tryAgain;
4908 
4909   case Stmt::OpaqueValueExprClass:
4910     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4911       E = src;
4912       goto tryAgain;
4913     }
4914     return SLCT_NotALiteral;
4915 
4916   case Stmt::PredefinedExprClass:
4917     // While __func__, etc., are technically not string literals, they
4918     // cannot contain format specifiers and thus are not a security
4919     // liability.
4920     return SLCT_UncheckedLiteral;
4921 
4922   case Stmt::DeclRefExprClass: {
4923     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4924 
4925     // As an exception, do not flag errors for variables binding to
4926     // const string literals.
4927     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4928       bool isConstant = false;
4929       QualType T = DR->getType();
4930 
4931       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4932         isConstant = AT->getElementType().isConstant(S.Context);
4933       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4934         isConstant = T.isConstant(S.Context) &&
4935                      PT->getPointeeType().isConstant(S.Context);
4936       } else if (T->isObjCObjectPointerType()) {
4937         // In ObjC, there is usually no "const ObjectPointer" type,
4938         // so don't check if the pointee type is constant.
4939         isConstant = T.isConstant(S.Context);
4940       }
4941 
4942       if (isConstant) {
4943         if (const Expr *Init = VD->getAnyInitializer()) {
4944           // Look through initializers like const char c[] = { "foo" }
4945           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4946             if (InitList->isStringLiteralInit())
4947               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4948           }
4949           return checkFormatStringExpr(S, Init, Args,
4950                                        HasVAListArg, format_idx,
4951                                        firstDataArg, Type, CallType,
4952                                        /*InFunctionCall*/ false, CheckedVarArgs,
4953                                        UncoveredArg, Offset);
4954         }
4955       }
4956 
4957       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4958       // special check to see if the format string is a function parameter
4959       // of the function calling the printf function.  If the function
4960       // has an attribute indicating it is a printf-like function, then we
4961       // should suppress warnings concerning non-literals being used in a call
4962       // to a vprintf function.  For example:
4963       //
4964       // void
4965       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4966       //      va_list ap;
4967       //      va_start(ap, fmt);
4968       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4969       //      ...
4970       // }
4971       if (HasVAListArg) {
4972         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4973           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4974             int PVIndex = PV->getFunctionScopeIndex() + 1;
4975             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4976               // adjust for implicit parameter
4977               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4978                 if (MD->isInstance())
4979                   ++PVIndex;
4980               // We also check if the formats are compatible.
4981               // We can't pass a 'scanf' string to a 'printf' function.
4982               if (PVIndex == PVFormat->getFormatIdx() &&
4983                   Type == S.GetFormatStringType(PVFormat))
4984                 return SLCT_UncheckedLiteral;
4985             }
4986           }
4987         }
4988       }
4989     }
4990 
4991     return SLCT_NotALiteral;
4992   }
4993 
4994   case Stmt::CallExprClass:
4995   case Stmt::CXXMemberCallExprClass: {
4996     const CallExpr *CE = cast<CallExpr>(E);
4997     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4998       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4999         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
5000         return checkFormatStringExpr(S, Arg, Args,
5001                                      HasVAListArg, format_idx, firstDataArg,
5002                                      Type, CallType, InFunctionCall,
5003                                      CheckedVarArgs, UncoveredArg, Offset);
5004       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5005         unsigned BuiltinID = FD->getBuiltinID();
5006         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5007             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5008           const Expr *Arg = CE->getArg(0);
5009           return checkFormatStringExpr(S, Arg, Args,
5010                                        HasVAListArg, format_idx,
5011                                        firstDataArg, Type, CallType,
5012                                        InFunctionCall, CheckedVarArgs,
5013                                        UncoveredArg, Offset);
5014         }
5015       }
5016     }
5017 
5018     return SLCT_NotALiteral;
5019   }
5020   case Stmt::ObjCMessageExprClass: {
5021     const auto *ME = cast<ObjCMessageExpr>(E);
5022     if (const auto *ND = ME->getMethodDecl()) {
5023       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5024         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
5025         return checkFormatStringExpr(
5026             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5027             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5028       }
5029     }
5030 
5031     return SLCT_NotALiteral;
5032   }
5033   case Stmt::ObjCStringLiteralClass:
5034   case Stmt::StringLiteralClass: {
5035     const StringLiteral *StrE = nullptr;
5036 
5037     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
5038       StrE = ObjCFExpr->getString();
5039     else
5040       StrE = cast<StringLiteral>(E);
5041 
5042     if (StrE) {
5043       if (Offset.isNegative() || Offset > StrE->getLength()) {
5044         // TODO: It would be better to have an explicit warning for out of
5045         // bounds literals.
5046         return SLCT_NotALiteral;
5047       }
5048       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5049       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5050                         firstDataArg, Type, InFunctionCall, CallType,
5051                         CheckedVarArgs, UncoveredArg);
5052       return SLCT_CheckedLiteral;
5053     }
5054 
5055     return SLCT_NotALiteral;
5056   }
5057   case Stmt::BinaryOperatorClass: {
5058     llvm::APSInt LResult;
5059     llvm::APSInt RResult;
5060 
5061     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5062 
5063     // A string literal + an int offset is still a string literal.
5064     if (BinOp->isAdditiveOp()) {
5065       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5066       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5067 
5068       if (LIsInt != RIsInt) {
5069         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5070 
5071         if (LIsInt) {
5072           if (BinOpKind == BO_Add) {
5073             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5074             E = BinOp->getRHS();
5075             goto tryAgain;
5076           }
5077         } else {
5078           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5079           E = BinOp->getLHS();
5080           goto tryAgain;
5081         }
5082       }
5083     }
5084 
5085     return SLCT_NotALiteral;
5086   }
5087   case Stmt::UnaryOperatorClass: {
5088     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5089     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5090     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
5091       llvm::APSInt IndexResult;
5092       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5093         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5094         E = ASE->getBase();
5095         goto tryAgain;
5096       }
5097     }
5098 
5099     return SLCT_NotALiteral;
5100   }
5101 
5102   default:
5103     return SLCT_NotALiteral;
5104   }
5105 }
5106 
5107 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5108   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5109       .Case("scanf", FST_Scanf)
5110       .Cases("printf", "printf0", FST_Printf)
5111       .Cases("NSString", "CFString", FST_NSString)
5112       .Case("strftime", FST_Strftime)
5113       .Case("strfmon", FST_Strfmon)
5114       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5115       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5116       .Case("os_trace", FST_OSLog)
5117       .Case("os_log", FST_OSLog)
5118       .Default(FST_Unknown);
5119 }
5120 
5121 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5122 /// functions) for correct use of format strings.
5123 /// Returns true if a format string has been fully checked.
5124 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5125                                 ArrayRef<const Expr *> Args,
5126                                 bool IsCXXMember,
5127                                 VariadicCallType CallType,
5128                                 SourceLocation Loc, SourceRange Range,
5129                                 llvm::SmallBitVector &CheckedVarArgs) {
5130   FormatStringInfo FSI;
5131   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5132     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5133                                 FSI.FirstDataArg, GetFormatStringType(Format),
5134                                 CallType, Loc, Range, CheckedVarArgs);
5135   return false;
5136 }
5137 
5138 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5139                                 bool HasVAListArg, unsigned format_idx,
5140                                 unsigned firstDataArg, FormatStringType Type,
5141                                 VariadicCallType CallType,
5142                                 SourceLocation Loc, SourceRange Range,
5143                                 llvm::SmallBitVector &CheckedVarArgs) {
5144   // CHECK: printf/scanf-like function is called with no format string.
5145   if (format_idx >= Args.size()) {
5146     Diag(Loc, diag::warn_missing_format_string) << Range;
5147     return false;
5148   }
5149 
5150   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5151 
5152   // CHECK: format string is not a string literal.
5153   //
5154   // Dynamically generated format strings are difficult to
5155   // automatically vet at compile time.  Requiring that format strings
5156   // are string literals: (1) permits the checking of format strings by
5157   // the compiler and thereby (2) can practically remove the source of
5158   // many format string exploits.
5159 
5160   // Format string can be either ObjC string (e.g. @"%d") or
5161   // C string (e.g. "%d")
5162   // ObjC string uses the same format specifiers as C string, so we can use
5163   // the same format string checking logic for both ObjC and C strings.
5164   UncoveredArgHandler UncoveredArg;
5165   StringLiteralCheckType CT =
5166       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5167                             format_idx, firstDataArg, Type, CallType,
5168                             /*IsFunctionCall*/ true, CheckedVarArgs,
5169                             UncoveredArg,
5170                             /*no string offset*/ llvm::APSInt(64, false) = 0);
5171 
5172   // Generate a diagnostic where an uncovered argument is detected.
5173   if (UncoveredArg.hasUncoveredArg()) {
5174     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5175     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5176     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5177   }
5178 
5179   if (CT != SLCT_NotALiteral)
5180     // Literal format string found, check done!
5181     return CT == SLCT_CheckedLiteral;
5182 
5183   // Strftime is particular as it always uses a single 'time' argument,
5184   // so it is safe to pass a non-literal string.
5185   if (Type == FST_Strftime)
5186     return false;
5187 
5188   // Do not emit diag when the string param is a macro expansion and the
5189   // format is either NSString or CFString. This is a hack to prevent
5190   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5191   // which are usually used in place of NS and CF string literals.
5192   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5193   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5194     return false;
5195 
5196   // If there are no arguments specified, warn with -Wformat-security, otherwise
5197   // warn only with -Wformat-nonliteral.
5198   if (Args.size() == firstDataArg) {
5199     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5200       << OrigFormatExpr->getSourceRange();
5201     switch (Type) {
5202     default:
5203       break;
5204     case FST_Kprintf:
5205     case FST_FreeBSDKPrintf:
5206     case FST_Printf:
5207       Diag(FormatLoc, diag::note_format_security_fixit)
5208         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5209       break;
5210     case FST_NSString:
5211       Diag(FormatLoc, diag::note_format_security_fixit)
5212         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5213       break;
5214     }
5215   } else {
5216     Diag(FormatLoc, diag::warn_format_nonliteral)
5217       << OrigFormatExpr->getSourceRange();
5218   }
5219   return false;
5220 }
5221 
5222 namespace {
5223 
5224 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5225 protected:
5226   Sema &S;
5227   const FormatStringLiteral *FExpr;
5228   const Expr *OrigFormatExpr;
5229   const Sema::FormatStringType FSType;
5230   const unsigned FirstDataArg;
5231   const unsigned NumDataArgs;
5232   const char *Beg; // Start of format string.
5233   const bool HasVAListArg;
5234   ArrayRef<const Expr *> Args;
5235   unsigned FormatIdx;
5236   llvm::SmallBitVector CoveredArgs;
5237   bool usesPositionalArgs = false;
5238   bool atFirstArg = true;
5239   bool inFunctionCall;
5240   Sema::VariadicCallType CallType;
5241   llvm::SmallBitVector &CheckedVarArgs;
5242   UncoveredArgHandler &UncoveredArg;
5243 
5244 public:
5245   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5246                      const Expr *origFormatExpr,
5247                      const Sema::FormatStringType type, unsigned firstDataArg,
5248                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5249                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5250                      bool inFunctionCall, Sema::VariadicCallType callType,
5251                      llvm::SmallBitVector &CheckedVarArgs,
5252                      UncoveredArgHandler &UncoveredArg)
5253       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5254         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5255         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5256         inFunctionCall(inFunctionCall), CallType(callType),
5257         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5258     CoveredArgs.resize(numDataArgs);
5259     CoveredArgs.reset();
5260   }
5261 
5262   void DoneProcessing();
5263 
5264   void HandleIncompleteSpecifier(const char *startSpecifier,
5265                                  unsigned specifierLen) override;
5266 
5267   void HandleInvalidLengthModifier(
5268                            const analyze_format_string::FormatSpecifier &FS,
5269                            const analyze_format_string::ConversionSpecifier &CS,
5270                            const char *startSpecifier, unsigned specifierLen,
5271                            unsigned DiagID);
5272 
5273   void HandleNonStandardLengthModifier(
5274                     const analyze_format_string::FormatSpecifier &FS,
5275                     const char *startSpecifier, unsigned specifierLen);
5276 
5277   void HandleNonStandardConversionSpecifier(
5278                     const analyze_format_string::ConversionSpecifier &CS,
5279                     const char *startSpecifier, unsigned specifierLen);
5280 
5281   void HandlePosition(const char *startPos, unsigned posLen) override;
5282 
5283   void HandleInvalidPosition(const char *startSpecifier,
5284                              unsigned specifierLen,
5285                              analyze_format_string::PositionContext p) override;
5286 
5287   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5288 
5289   void HandleNullChar(const char *nullCharacter) override;
5290 
5291   template <typename Range>
5292   static void
5293   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5294                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5295                        bool IsStringLocation, Range StringRange,
5296                        ArrayRef<FixItHint> Fixit = None);
5297 
5298 protected:
5299   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5300                                         const char *startSpec,
5301                                         unsigned specifierLen,
5302                                         const char *csStart, unsigned csLen);
5303 
5304   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5305                                          const char *startSpec,
5306                                          unsigned specifierLen);
5307 
5308   SourceRange getFormatStringRange();
5309   CharSourceRange getSpecifierRange(const char *startSpecifier,
5310                                     unsigned specifierLen);
5311   SourceLocation getLocationOfByte(const char *x);
5312 
5313   const Expr *getDataArg(unsigned i) const;
5314 
5315   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5316                     const analyze_format_string::ConversionSpecifier &CS,
5317                     const char *startSpecifier, unsigned specifierLen,
5318                     unsigned argIndex);
5319 
5320   template <typename Range>
5321   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5322                             bool IsStringLocation, Range StringRange,
5323                             ArrayRef<FixItHint> Fixit = None);
5324 };
5325 
5326 } // namespace
5327 
5328 SourceRange CheckFormatHandler::getFormatStringRange() {
5329   return OrigFormatExpr->getSourceRange();
5330 }
5331 
5332 CharSourceRange CheckFormatHandler::
5333 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5334   SourceLocation Start = getLocationOfByte(startSpecifier);
5335   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5336 
5337   // Advance the end SourceLocation by one due to half-open ranges.
5338   End = End.getLocWithOffset(1);
5339 
5340   return CharSourceRange::getCharRange(Start, End);
5341 }
5342 
5343 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5344   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5345                                   S.getLangOpts(), S.Context.getTargetInfo());
5346 }
5347 
5348 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5349                                                    unsigned specifierLen){
5350   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5351                        getLocationOfByte(startSpecifier),
5352                        /*IsStringLocation*/true,
5353                        getSpecifierRange(startSpecifier, specifierLen));
5354 }
5355 
5356 void CheckFormatHandler::HandleInvalidLengthModifier(
5357     const analyze_format_string::FormatSpecifier &FS,
5358     const analyze_format_string::ConversionSpecifier &CS,
5359     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5360   using namespace analyze_format_string;
5361 
5362   const LengthModifier &LM = FS.getLengthModifier();
5363   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5364 
5365   // See if we know how to fix this length modifier.
5366   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5367   if (FixedLM) {
5368     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5369                          getLocationOfByte(LM.getStart()),
5370                          /*IsStringLocation*/true,
5371                          getSpecifierRange(startSpecifier, specifierLen));
5372 
5373     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5374       << FixedLM->toString()
5375       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5376 
5377   } else {
5378     FixItHint Hint;
5379     if (DiagID == diag::warn_format_nonsensical_length)
5380       Hint = FixItHint::CreateRemoval(LMRange);
5381 
5382     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5383                          getLocationOfByte(LM.getStart()),
5384                          /*IsStringLocation*/true,
5385                          getSpecifierRange(startSpecifier, specifierLen),
5386                          Hint);
5387   }
5388 }
5389 
5390 void CheckFormatHandler::HandleNonStandardLengthModifier(
5391     const analyze_format_string::FormatSpecifier &FS,
5392     const char *startSpecifier, unsigned specifierLen) {
5393   using namespace analyze_format_string;
5394 
5395   const LengthModifier &LM = FS.getLengthModifier();
5396   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5397 
5398   // See if we know how to fix this length modifier.
5399   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5400   if (FixedLM) {
5401     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5402                            << LM.toString() << 0,
5403                          getLocationOfByte(LM.getStart()),
5404                          /*IsStringLocation*/true,
5405                          getSpecifierRange(startSpecifier, specifierLen));
5406 
5407     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5408       << FixedLM->toString()
5409       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5410 
5411   } else {
5412     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5413                            << LM.toString() << 0,
5414                          getLocationOfByte(LM.getStart()),
5415                          /*IsStringLocation*/true,
5416                          getSpecifierRange(startSpecifier, specifierLen));
5417   }
5418 }
5419 
5420 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5421     const analyze_format_string::ConversionSpecifier &CS,
5422     const char *startSpecifier, unsigned specifierLen) {
5423   using namespace analyze_format_string;
5424 
5425   // See if we know how to fix this conversion specifier.
5426   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5427   if (FixedCS) {
5428     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5429                           << CS.toString() << /*conversion specifier*/1,
5430                          getLocationOfByte(CS.getStart()),
5431                          /*IsStringLocation*/true,
5432                          getSpecifierRange(startSpecifier, specifierLen));
5433 
5434     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5435     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5436       << FixedCS->toString()
5437       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5438   } else {
5439     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5440                           << CS.toString() << /*conversion specifier*/1,
5441                          getLocationOfByte(CS.getStart()),
5442                          /*IsStringLocation*/true,
5443                          getSpecifierRange(startSpecifier, specifierLen));
5444   }
5445 }
5446 
5447 void CheckFormatHandler::HandlePosition(const char *startPos,
5448                                         unsigned posLen) {
5449   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5450                                getLocationOfByte(startPos),
5451                                /*IsStringLocation*/true,
5452                                getSpecifierRange(startPos, posLen));
5453 }
5454 
5455 void
5456 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5457                                      analyze_format_string::PositionContext p) {
5458   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5459                          << (unsigned) p,
5460                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5461                        getSpecifierRange(startPos, posLen));
5462 }
5463 
5464 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5465                                             unsigned posLen) {
5466   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5467                                getLocationOfByte(startPos),
5468                                /*IsStringLocation*/true,
5469                                getSpecifierRange(startPos, posLen));
5470 }
5471 
5472 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5473   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5474     // The presence of a null character is likely an error.
5475     EmitFormatDiagnostic(
5476       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5477       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5478       getFormatStringRange());
5479   }
5480 }
5481 
5482 // Note that this may return NULL if there was an error parsing or building
5483 // one of the argument expressions.
5484 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5485   return Args[FirstDataArg + i];
5486 }
5487 
5488 void CheckFormatHandler::DoneProcessing() {
5489   // Does the number of data arguments exceed the number of
5490   // format conversions in the format string?
5491   if (!HasVAListArg) {
5492       // Find any arguments that weren't covered.
5493     CoveredArgs.flip();
5494     signed notCoveredArg = CoveredArgs.find_first();
5495     if (notCoveredArg >= 0) {
5496       assert((unsigned)notCoveredArg < NumDataArgs);
5497       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5498     } else {
5499       UncoveredArg.setAllCovered();
5500     }
5501   }
5502 }
5503 
5504 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5505                                    const Expr *ArgExpr) {
5506   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5507          "Invalid state");
5508 
5509   if (!ArgExpr)
5510     return;
5511 
5512   SourceLocation Loc = ArgExpr->getLocStart();
5513 
5514   if (S.getSourceManager().isInSystemMacro(Loc))
5515     return;
5516 
5517   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5518   for (auto E : DiagnosticExprs)
5519     PDiag << E->getSourceRange();
5520 
5521   CheckFormatHandler::EmitFormatDiagnostic(
5522                                   S, IsFunctionCall, DiagnosticExprs[0],
5523                                   PDiag, Loc, /*IsStringLocation*/false,
5524                                   DiagnosticExprs[0]->getSourceRange());
5525 }
5526 
5527 bool
5528 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5529                                                      SourceLocation Loc,
5530                                                      const char *startSpec,
5531                                                      unsigned specifierLen,
5532                                                      const char *csStart,
5533                                                      unsigned csLen) {
5534   bool keepGoing = true;
5535   if (argIndex < NumDataArgs) {
5536     // Consider the argument coverered, even though the specifier doesn't
5537     // make sense.
5538     CoveredArgs.set(argIndex);
5539   }
5540   else {
5541     // If argIndex exceeds the number of data arguments we
5542     // don't issue a warning because that is just a cascade of warnings (and
5543     // they may have intended '%%' anyway). We don't want to continue processing
5544     // the format string after this point, however, as we will like just get
5545     // gibberish when trying to match arguments.
5546     keepGoing = false;
5547   }
5548 
5549   StringRef Specifier(csStart, csLen);
5550 
5551   // If the specifier in non-printable, it could be the first byte of a UTF-8
5552   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5553   // hex value.
5554   std::string CodePointStr;
5555   if (!llvm::sys::locale::isPrint(*csStart)) {
5556     llvm::UTF32 CodePoint;
5557     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5558     const llvm::UTF8 *E =
5559         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5560     llvm::ConversionResult Result =
5561         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5562 
5563     if (Result != llvm::conversionOK) {
5564       unsigned char FirstChar = *csStart;
5565       CodePoint = (llvm::UTF32)FirstChar;
5566     }
5567 
5568     llvm::raw_string_ostream OS(CodePointStr);
5569     if (CodePoint < 256)
5570       OS << "\\x" << llvm::format("%02x", CodePoint);
5571     else if (CodePoint <= 0xFFFF)
5572       OS << "\\u" << llvm::format("%04x", CodePoint);
5573     else
5574       OS << "\\U" << llvm::format("%08x", CodePoint);
5575     OS.flush();
5576     Specifier = CodePointStr;
5577   }
5578 
5579   EmitFormatDiagnostic(
5580       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5581       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5582 
5583   return keepGoing;
5584 }
5585 
5586 void
5587 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5588                                                       const char *startSpec,
5589                                                       unsigned specifierLen) {
5590   EmitFormatDiagnostic(
5591     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5592     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5593 }
5594 
5595 bool
5596 CheckFormatHandler::CheckNumArgs(
5597   const analyze_format_string::FormatSpecifier &FS,
5598   const analyze_format_string::ConversionSpecifier &CS,
5599   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5600 
5601   if (argIndex >= NumDataArgs) {
5602     PartialDiagnostic PDiag = FS.usesPositionalArg()
5603       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5604            << (argIndex+1) << NumDataArgs)
5605       : S.PDiag(diag::warn_printf_insufficient_data_args);
5606     EmitFormatDiagnostic(
5607       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5608       getSpecifierRange(startSpecifier, specifierLen));
5609 
5610     // Since more arguments than conversion tokens are given, by extension
5611     // all arguments are covered, so mark this as so.
5612     UncoveredArg.setAllCovered();
5613     return false;
5614   }
5615   return true;
5616 }
5617 
5618 template<typename Range>
5619 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5620                                               SourceLocation Loc,
5621                                               bool IsStringLocation,
5622                                               Range StringRange,
5623                                               ArrayRef<FixItHint> FixIt) {
5624   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5625                        Loc, IsStringLocation, StringRange, FixIt);
5626 }
5627 
5628 /// \brief If the format string is not within the funcion call, emit a note
5629 /// so that the function call and string are in diagnostic messages.
5630 ///
5631 /// \param InFunctionCall if true, the format string is within the function
5632 /// call and only one diagnostic message will be produced.  Otherwise, an
5633 /// extra note will be emitted pointing to location of the format string.
5634 ///
5635 /// \param ArgumentExpr the expression that is passed as the format string
5636 /// argument in the function call.  Used for getting locations when two
5637 /// diagnostics are emitted.
5638 ///
5639 /// \param PDiag the callee should already have provided any strings for the
5640 /// diagnostic message.  This function only adds locations and fixits
5641 /// to diagnostics.
5642 ///
5643 /// \param Loc primary location for diagnostic.  If two diagnostics are
5644 /// required, one will be at Loc and a new SourceLocation will be created for
5645 /// the other one.
5646 ///
5647 /// \param IsStringLocation if true, Loc points to the format string should be
5648 /// used for the note.  Otherwise, Loc points to the argument list and will
5649 /// be used with PDiag.
5650 ///
5651 /// \param StringRange some or all of the string to highlight.  This is
5652 /// templated so it can accept either a CharSourceRange or a SourceRange.
5653 ///
5654 /// \param FixIt optional fix it hint for the format string.
5655 template <typename Range>
5656 void CheckFormatHandler::EmitFormatDiagnostic(
5657     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5658     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5659     Range StringRange, ArrayRef<FixItHint> FixIt) {
5660   if (InFunctionCall) {
5661     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5662     D << StringRange;
5663     D << FixIt;
5664   } else {
5665     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5666       << ArgumentExpr->getSourceRange();
5667 
5668     const Sema::SemaDiagnosticBuilder &Note =
5669       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5670              diag::note_format_string_defined);
5671 
5672     Note << StringRange;
5673     Note << FixIt;
5674   }
5675 }
5676 
5677 //===--- CHECK: Printf format string checking ------------------------------===//
5678 
5679 namespace {
5680 
5681 class CheckPrintfHandler : public CheckFormatHandler {
5682 public:
5683   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5684                      const Expr *origFormatExpr,
5685                      const Sema::FormatStringType type, unsigned firstDataArg,
5686                      unsigned numDataArgs, bool isObjC, const char *beg,
5687                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5688                      unsigned formatIdx, bool inFunctionCall,
5689                      Sema::VariadicCallType CallType,
5690                      llvm::SmallBitVector &CheckedVarArgs,
5691                      UncoveredArgHandler &UncoveredArg)
5692       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5693                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5694                            inFunctionCall, CallType, CheckedVarArgs,
5695                            UncoveredArg) {}
5696 
5697   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5698 
5699   /// Returns true if '%@' specifiers are allowed in the format string.
5700   bool allowsObjCArg() const {
5701     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5702            FSType == Sema::FST_OSTrace;
5703   }
5704 
5705   bool HandleInvalidPrintfConversionSpecifier(
5706                                       const analyze_printf::PrintfSpecifier &FS,
5707                                       const char *startSpecifier,
5708                                       unsigned specifierLen) override;
5709 
5710   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5711                              const char *startSpecifier,
5712                              unsigned specifierLen) override;
5713   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5714                        const char *StartSpecifier,
5715                        unsigned SpecifierLen,
5716                        const Expr *E);
5717 
5718   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5719                     const char *startSpecifier, unsigned specifierLen);
5720   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5721                            const analyze_printf::OptionalAmount &Amt,
5722                            unsigned type,
5723                            const char *startSpecifier, unsigned specifierLen);
5724   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5725                   const analyze_printf::OptionalFlag &flag,
5726                   const char *startSpecifier, unsigned specifierLen);
5727   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5728                          const analyze_printf::OptionalFlag &ignoredFlag,
5729                          const analyze_printf::OptionalFlag &flag,
5730                          const char *startSpecifier, unsigned specifierLen);
5731   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5732                            const Expr *E);
5733 
5734   void HandleEmptyObjCModifierFlag(const char *startFlag,
5735                                    unsigned flagLen) override;
5736 
5737   void HandleInvalidObjCModifierFlag(const char *startFlag,
5738                                             unsigned flagLen) override;
5739 
5740   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5741                                            const char *flagsEnd,
5742                                            const char *conversionPosition)
5743                                              override;
5744 };
5745 
5746 } // namespace
5747 
5748 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5749                                       const analyze_printf::PrintfSpecifier &FS,
5750                                       const char *startSpecifier,
5751                                       unsigned specifierLen) {
5752   const analyze_printf::PrintfConversionSpecifier &CS =
5753     FS.getConversionSpecifier();
5754 
5755   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5756                                           getLocationOfByte(CS.getStart()),
5757                                           startSpecifier, specifierLen,
5758                                           CS.getStart(), CS.getLength());
5759 }
5760 
5761 bool CheckPrintfHandler::HandleAmount(
5762                                const analyze_format_string::OptionalAmount &Amt,
5763                                unsigned k, const char *startSpecifier,
5764                                unsigned specifierLen) {
5765   if (Amt.hasDataArgument()) {
5766     if (!HasVAListArg) {
5767       unsigned argIndex = Amt.getArgIndex();
5768       if (argIndex >= NumDataArgs) {
5769         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5770                                << k,
5771                              getLocationOfByte(Amt.getStart()),
5772                              /*IsStringLocation*/true,
5773                              getSpecifierRange(startSpecifier, specifierLen));
5774         // Don't do any more checking.  We will just emit
5775         // spurious errors.
5776         return false;
5777       }
5778 
5779       // Type check the data argument.  It should be an 'int'.
5780       // Although not in conformance with C99, we also allow the argument to be
5781       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5782       // doesn't emit a warning for that case.
5783       CoveredArgs.set(argIndex);
5784       const Expr *Arg = getDataArg(argIndex);
5785       if (!Arg)
5786         return false;
5787 
5788       QualType T = Arg->getType();
5789 
5790       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5791       assert(AT.isValid());
5792 
5793       if (!AT.matchesType(S.Context, T)) {
5794         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5795                                << k << AT.getRepresentativeTypeName(S.Context)
5796                                << T << Arg->getSourceRange(),
5797                              getLocationOfByte(Amt.getStart()),
5798                              /*IsStringLocation*/true,
5799                              getSpecifierRange(startSpecifier, specifierLen));
5800         // Don't do any more checking.  We will just emit
5801         // spurious errors.
5802         return false;
5803       }
5804     }
5805   }
5806   return true;
5807 }
5808 
5809 void CheckPrintfHandler::HandleInvalidAmount(
5810                                       const analyze_printf::PrintfSpecifier &FS,
5811                                       const analyze_printf::OptionalAmount &Amt,
5812                                       unsigned type,
5813                                       const char *startSpecifier,
5814                                       unsigned specifierLen) {
5815   const analyze_printf::PrintfConversionSpecifier &CS =
5816     FS.getConversionSpecifier();
5817 
5818   FixItHint fixit =
5819     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5820       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5821                                  Amt.getConstantLength()))
5822       : FixItHint();
5823 
5824   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5825                          << type << CS.toString(),
5826                        getLocationOfByte(Amt.getStart()),
5827                        /*IsStringLocation*/true,
5828                        getSpecifierRange(startSpecifier, specifierLen),
5829                        fixit);
5830 }
5831 
5832 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5833                                     const analyze_printf::OptionalFlag &flag,
5834                                     const char *startSpecifier,
5835                                     unsigned specifierLen) {
5836   // Warn about pointless flag with a fixit removal.
5837   const analyze_printf::PrintfConversionSpecifier &CS =
5838     FS.getConversionSpecifier();
5839   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5840                          << flag.toString() << CS.toString(),
5841                        getLocationOfByte(flag.getPosition()),
5842                        /*IsStringLocation*/true,
5843                        getSpecifierRange(startSpecifier, specifierLen),
5844                        FixItHint::CreateRemoval(
5845                          getSpecifierRange(flag.getPosition(), 1)));
5846 }
5847 
5848 void CheckPrintfHandler::HandleIgnoredFlag(
5849                                 const analyze_printf::PrintfSpecifier &FS,
5850                                 const analyze_printf::OptionalFlag &ignoredFlag,
5851                                 const analyze_printf::OptionalFlag &flag,
5852                                 const char *startSpecifier,
5853                                 unsigned specifierLen) {
5854   // Warn about ignored flag with a fixit removal.
5855   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5856                          << ignoredFlag.toString() << flag.toString(),
5857                        getLocationOfByte(ignoredFlag.getPosition()),
5858                        /*IsStringLocation*/true,
5859                        getSpecifierRange(startSpecifier, specifierLen),
5860                        FixItHint::CreateRemoval(
5861                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5862 }
5863 
5864 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5865                                                      unsigned flagLen) {
5866   // Warn about an empty flag.
5867   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5868                        getLocationOfByte(startFlag),
5869                        /*IsStringLocation*/true,
5870                        getSpecifierRange(startFlag, flagLen));
5871 }
5872 
5873 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5874                                                        unsigned flagLen) {
5875   // Warn about an invalid flag.
5876   auto Range = getSpecifierRange(startFlag, flagLen);
5877   StringRef flag(startFlag, flagLen);
5878   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5879                       getLocationOfByte(startFlag),
5880                       /*IsStringLocation*/true,
5881                       Range, FixItHint::CreateRemoval(Range));
5882 }
5883 
5884 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5885     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5886     // Warn about using '[...]' without a '@' conversion.
5887     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5888     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5889     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5890                          getLocationOfByte(conversionPosition),
5891                          /*IsStringLocation*/true,
5892                          Range, FixItHint::CreateRemoval(Range));
5893 }
5894 
5895 // Determines if the specified is a C++ class or struct containing
5896 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5897 // "c_str()").
5898 template<typename MemberKind>
5899 static llvm::SmallPtrSet<MemberKind*, 1>
5900 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5901   const RecordType *RT = Ty->getAs<RecordType>();
5902   llvm::SmallPtrSet<MemberKind*, 1> Results;
5903 
5904   if (!RT)
5905     return Results;
5906   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5907   if (!RD || !RD->getDefinition())
5908     return Results;
5909 
5910   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5911                  Sema::LookupMemberName);
5912   R.suppressDiagnostics();
5913 
5914   // We just need to include all members of the right kind turned up by the
5915   // filter, at this point.
5916   if (S.LookupQualifiedName(R, RT->getDecl()))
5917     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5918       NamedDecl *decl = (*I)->getUnderlyingDecl();
5919       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5920         Results.insert(FK);
5921     }
5922   return Results;
5923 }
5924 
5925 /// Check if we could call '.c_str()' on an object.
5926 ///
5927 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5928 /// allow the call, or if it would be ambiguous).
5929 bool Sema::hasCStrMethod(const Expr *E) {
5930   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5931 
5932   MethodSet Results =
5933       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5934   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5935        MI != ME; ++MI)
5936     if ((*MI)->getMinRequiredArguments() == 0)
5937       return true;
5938   return false;
5939 }
5940 
5941 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5942 // better diagnostic if so. AT is assumed to be valid.
5943 // Returns true when a c_str() conversion method is found.
5944 bool CheckPrintfHandler::checkForCStrMembers(
5945     const analyze_printf::ArgType &AT, const Expr *E) {
5946   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5947 
5948   MethodSet Results =
5949       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5950 
5951   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5952        MI != ME; ++MI) {
5953     const CXXMethodDecl *Method = *MI;
5954     if (Method->getMinRequiredArguments() == 0 &&
5955         AT.matchesType(S.Context, Method->getReturnType())) {
5956       // FIXME: Suggest parens if the expression needs them.
5957       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5958       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5959           << "c_str()"
5960           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5961       return true;
5962     }
5963   }
5964 
5965   return false;
5966 }
5967 
5968 bool
5969 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5970                                             &FS,
5971                                           const char *startSpecifier,
5972                                           unsigned specifierLen) {
5973   using namespace analyze_format_string;
5974   using namespace analyze_printf;
5975 
5976   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5977 
5978   if (FS.consumesDataArgument()) {
5979     if (atFirstArg) {
5980         atFirstArg = false;
5981         usesPositionalArgs = FS.usesPositionalArg();
5982     }
5983     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5984       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5985                                         startSpecifier, specifierLen);
5986       return false;
5987     }
5988   }
5989 
5990   // First check if the field width, precision, and conversion specifier
5991   // have matching data arguments.
5992   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5993                     startSpecifier, specifierLen)) {
5994     return false;
5995   }
5996 
5997   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5998                     startSpecifier, specifierLen)) {
5999     return false;
6000   }
6001 
6002   if (!CS.consumesDataArgument()) {
6003     // FIXME: Technically specifying a precision or field width here
6004     // makes no sense.  Worth issuing a warning at some point.
6005     return true;
6006   }
6007 
6008   // Consume the argument.
6009   unsigned argIndex = FS.getArgIndex();
6010   if (argIndex < NumDataArgs) {
6011     // The check to see if the argIndex is valid will come later.
6012     // We set the bit here because we may exit early from this
6013     // function if we encounter some other error.
6014     CoveredArgs.set(argIndex);
6015   }
6016 
6017   // FreeBSD kernel extensions.
6018   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6019       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6020     // We need at least two arguments.
6021     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6022       return false;
6023 
6024     // Claim the second argument.
6025     CoveredArgs.set(argIndex + 1);
6026 
6027     // Type check the first argument (int for %b, pointer for %D)
6028     const Expr *Ex = getDataArg(argIndex);
6029     const analyze_printf::ArgType &AT =
6030       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6031         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6032     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6033       EmitFormatDiagnostic(
6034         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6035         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6036         << false << Ex->getSourceRange(),
6037         Ex->getLocStart(), /*IsStringLocation*/false,
6038         getSpecifierRange(startSpecifier, specifierLen));
6039 
6040     // Type check the second argument (char * for both %b and %D)
6041     Ex = getDataArg(argIndex + 1);
6042     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6043     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6044       EmitFormatDiagnostic(
6045         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6046         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6047         << false << Ex->getSourceRange(),
6048         Ex->getLocStart(), /*IsStringLocation*/false,
6049         getSpecifierRange(startSpecifier, specifierLen));
6050 
6051      return true;
6052   }
6053 
6054   // Check for using an Objective-C specific conversion specifier
6055   // in a non-ObjC literal.
6056   if (!allowsObjCArg() && CS.isObjCArg()) {
6057     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6058                                                   specifierLen);
6059   }
6060 
6061   // %P can only be used with os_log.
6062   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6063     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6064                                                   specifierLen);
6065   }
6066 
6067   // %n is not allowed with os_log.
6068   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6069     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6070                          getLocationOfByte(CS.getStart()),
6071                          /*IsStringLocation*/ false,
6072                          getSpecifierRange(startSpecifier, specifierLen));
6073 
6074     return true;
6075   }
6076 
6077   // Only scalars are allowed for os_trace.
6078   if (FSType == Sema::FST_OSTrace &&
6079       (CS.getKind() == ConversionSpecifier::PArg ||
6080        CS.getKind() == ConversionSpecifier::sArg ||
6081        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6082     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6083                                                   specifierLen);
6084   }
6085 
6086   // Check for use of public/private annotation outside of os_log().
6087   if (FSType != Sema::FST_OSLog) {
6088     if (FS.isPublic().isSet()) {
6089       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6090                                << "public",
6091                            getLocationOfByte(FS.isPublic().getPosition()),
6092                            /*IsStringLocation*/ false,
6093                            getSpecifierRange(startSpecifier, specifierLen));
6094     }
6095     if (FS.isPrivate().isSet()) {
6096       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6097                                << "private",
6098                            getLocationOfByte(FS.isPrivate().getPosition()),
6099                            /*IsStringLocation*/ false,
6100                            getSpecifierRange(startSpecifier, specifierLen));
6101     }
6102   }
6103 
6104   // Check for invalid use of field width
6105   if (!FS.hasValidFieldWidth()) {
6106     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6107         startSpecifier, specifierLen);
6108   }
6109 
6110   // Check for invalid use of precision
6111   if (!FS.hasValidPrecision()) {
6112     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6113         startSpecifier, specifierLen);
6114   }
6115 
6116   // Precision is mandatory for %P specifier.
6117   if (CS.getKind() == ConversionSpecifier::PArg &&
6118       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6119     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6120                          getLocationOfByte(startSpecifier),
6121                          /*IsStringLocation*/ false,
6122                          getSpecifierRange(startSpecifier, specifierLen));
6123   }
6124 
6125   // Check each flag does not conflict with any other component.
6126   if (!FS.hasValidThousandsGroupingPrefix())
6127     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6128   if (!FS.hasValidLeadingZeros())
6129     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6130   if (!FS.hasValidPlusPrefix())
6131     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6132   if (!FS.hasValidSpacePrefix())
6133     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6134   if (!FS.hasValidAlternativeForm())
6135     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6136   if (!FS.hasValidLeftJustified())
6137     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6138 
6139   // Check that flags are not ignored by another flag
6140   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6141     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6142         startSpecifier, specifierLen);
6143   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6144     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6145             startSpecifier, specifierLen);
6146 
6147   // Check the length modifier is valid with the given conversion specifier.
6148   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6149     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6150                                 diag::warn_format_nonsensical_length);
6151   else if (!FS.hasStandardLengthModifier())
6152     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6153   else if (!FS.hasStandardLengthConversionCombination())
6154     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6155                                 diag::warn_format_non_standard_conversion_spec);
6156 
6157   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6158     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6159 
6160   // The remaining checks depend on the data arguments.
6161   if (HasVAListArg)
6162     return true;
6163 
6164   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6165     return false;
6166 
6167   const Expr *Arg = getDataArg(argIndex);
6168   if (!Arg)
6169     return true;
6170 
6171   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6172 }
6173 
6174 static bool requiresParensToAddCast(const Expr *E) {
6175   // FIXME: We should have a general way to reason about operator
6176   // precedence and whether parens are actually needed here.
6177   // Take care of a few common cases where they aren't.
6178   const Expr *Inside = E->IgnoreImpCasts();
6179   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6180     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6181 
6182   switch (Inside->getStmtClass()) {
6183   case Stmt::ArraySubscriptExprClass:
6184   case Stmt::CallExprClass:
6185   case Stmt::CharacterLiteralClass:
6186   case Stmt::CXXBoolLiteralExprClass:
6187   case Stmt::DeclRefExprClass:
6188   case Stmt::FloatingLiteralClass:
6189   case Stmt::IntegerLiteralClass:
6190   case Stmt::MemberExprClass:
6191   case Stmt::ObjCArrayLiteralClass:
6192   case Stmt::ObjCBoolLiteralExprClass:
6193   case Stmt::ObjCBoxedExprClass:
6194   case Stmt::ObjCDictionaryLiteralClass:
6195   case Stmt::ObjCEncodeExprClass:
6196   case Stmt::ObjCIvarRefExprClass:
6197   case Stmt::ObjCMessageExprClass:
6198   case Stmt::ObjCPropertyRefExprClass:
6199   case Stmt::ObjCStringLiteralClass:
6200   case Stmt::ObjCSubscriptRefExprClass:
6201   case Stmt::ParenExprClass:
6202   case Stmt::StringLiteralClass:
6203   case Stmt::UnaryOperatorClass:
6204     return false;
6205   default:
6206     return true;
6207   }
6208 }
6209 
6210 static std::pair<QualType, StringRef>
6211 shouldNotPrintDirectly(const ASTContext &Context,
6212                        QualType IntendedTy,
6213                        const Expr *E) {
6214   // Use a 'while' to peel off layers of typedefs.
6215   QualType TyTy = IntendedTy;
6216   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6217     StringRef Name = UserTy->getDecl()->getName();
6218     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6219       .Case("CFIndex", Context.getNSIntegerType())
6220       .Case("NSInteger", Context.getNSIntegerType())
6221       .Case("NSUInteger", Context.getNSUIntegerType())
6222       .Case("SInt32", Context.IntTy)
6223       .Case("UInt32", Context.UnsignedIntTy)
6224       .Default(QualType());
6225 
6226     if (!CastTy.isNull())
6227       return std::make_pair(CastTy, Name);
6228 
6229     TyTy = UserTy->desugar();
6230   }
6231 
6232   // Strip parens if necessary.
6233   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6234     return shouldNotPrintDirectly(Context,
6235                                   PE->getSubExpr()->getType(),
6236                                   PE->getSubExpr());
6237 
6238   // If this is a conditional expression, then its result type is constructed
6239   // via usual arithmetic conversions and thus there might be no necessary
6240   // typedef sugar there.  Recurse to operands to check for NSInteger &
6241   // Co. usage condition.
6242   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6243     QualType TrueTy, FalseTy;
6244     StringRef TrueName, FalseName;
6245 
6246     std::tie(TrueTy, TrueName) =
6247       shouldNotPrintDirectly(Context,
6248                              CO->getTrueExpr()->getType(),
6249                              CO->getTrueExpr());
6250     std::tie(FalseTy, FalseName) =
6251       shouldNotPrintDirectly(Context,
6252                              CO->getFalseExpr()->getType(),
6253                              CO->getFalseExpr());
6254 
6255     if (TrueTy == FalseTy)
6256       return std::make_pair(TrueTy, TrueName);
6257     else if (TrueTy.isNull())
6258       return std::make_pair(FalseTy, FalseName);
6259     else if (FalseTy.isNull())
6260       return std::make_pair(TrueTy, TrueName);
6261   }
6262 
6263   return std::make_pair(QualType(), StringRef());
6264 }
6265 
6266 bool
6267 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6268                                     const char *StartSpecifier,
6269                                     unsigned SpecifierLen,
6270                                     const Expr *E) {
6271   using namespace analyze_format_string;
6272   using namespace analyze_printf;
6273 
6274   // Now type check the data expression that matches the
6275   // format specifier.
6276   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6277   if (!AT.isValid())
6278     return true;
6279 
6280   QualType ExprTy = E->getType();
6281   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6282     ExprTy = TET->getUnderlyingExpr()->getType();
6283   }
6284 
6285   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6286 
6287   if (match == analyze_printf::ArgType::Match) {
6288     return true;
6289   }
6290 
6291   // Look through argument promotions for our error message's reported type.
6292   // This includes the integral and floating promotions, but excludes array
6293   // and function pointer decay; seeing that an argument intended to be a
6294   // string has type 'char [6]' is probably more confusing than 'char *'.
6295   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6296     if (ICE->getCastKind() == CK_IntegralCast ||
6297         ICE->getCastKind() == CK_FloatingCast) {
6298       E = ICE->getSubExpr();
6299       ExprTy = E->getType();
6300 
6301       // Check if we didn't match because of an implicit cast from a 'char'
6302       // or 'short' to an 'int'.  This is done because printf is a varargs
6303       // function.
6304       if (ICE->getType() == S.Context.IntTy ||
6305           ICE->getType() == S.Context.UnsignedIntTy) {
6306         // All further checking is done on the subexpression.
6307         if (AT.matchesType(S.Context, ExprTy))
6308           return true;
6309       }
6310     }
6311   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6312     // Special case for 'a', which has type 'int' in C.
6313     // Note, however, that we do /not/ want to treat multibyte constants like
6314     // 'MooV' as characters! This form is deprecated but still exists.
6315     if (ExprTy == S.Context.IntTy)
6316       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6317         ExprTy = S.Context.CharTy;
6318   }
6319 
6320   // Look through enums to their underlying type.
6321   bool IsEnum = false;
6322   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6323     ExprTy = EnumTy->getDecl()->getIntegerType();
6324     IsEnum = true;
6325   }
6326 
6327   // %C in an Objective-C context prints a unichar, not a wchar_t.
6328   // If the argument is an integer of some kind, believe the %C and suggest
6329   // a cast instead of changing the conversion specifier.
6330   QualType IntendedTy = ExprTy;
6331   if (isObjCContext() &&
6332       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6333     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6334         !ExprTy->isCharType()) {
6335       // 'unichar' is defined as a typedef of unsigned short, but we should
6336       // prefer using the typedef if it is visible.
6337       IntendedTy = S.Context.UnsignedShortTy;
6338 
6339       // While we are here, check if the value is an IntegerLiteral that happens
6340       // to be within the valid range.
6341       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6342         const llvm::APInt &V = IL->getValue();
6343         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6344           return true;
6345       }
6346 
6347       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6348                           Sema::LookupOrdinaryName);
6349       if (S.LookupName(Result, S.getCurScope())) {
6350         NamedDecl *ND = Result.getFoundDecl();
6351         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6352           if (TD->getUnderlyingType() == IntendedTy)
6353             IntendedTy = S.Context.getTypedefType(TD);
6354       }
6355     }
6356   }
6357 
6358   // Special-case some of Darwin's platform-independence types by suggesting
6359   // casts to primitive types that are known to be large enough.
6360   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6361   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6362     QualType CastTy;
6363     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6364     if (!CastTy.isNull()) {
6365       IntendedTy = CastTy;
6366       ShouldNotPrintDirectly = true;
6367     }
6368   }
6369 
6370   // We may be able to offer a FixItHint if it is a supported type.
6371   PrintfSpecifier fixedFS = FS;
6372   bool success =
6373       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6374 
6375   if (success) {
6376     // Get the fix string from the fixed format specifier
6377     SmallString<16> buf;
6378     llvm::raw_svector_ostream os(buf);
6379     fixedFS.toString(os);
6380 
6381     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6382 
6383     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6384       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6385       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6386         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6387       }
6388       // In this case, the specifier is wrong and should be changed to match
6389       // the argument.
6390       EmitFormatDiagnostic(S.PDiag(diag)
6391                                << AT.getRepresentativeTypeName(S.Context)
6392                                << IntendedTy << IsEnum << E->getSourceRange(),
6393                            E->getLocStart(),
6394                            /*IsStringLocation*/ false, SpecRange,
6395                            FixItHint::CreateReplacement(SpecRange, os.str()));
6396     } else {
6397       // The canonical type for formatting this value is different from the
6398       // actual type of the expression. (This occurs, for example, with Darwin's
6399       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6400       // should be printed as 'long' for 64-bit compatibility.)
6401       // Rather than emitting a normal format/argument mismatch, we want to
6402       // add a cast to the recommended type (and correct the format string
6403       // if necessary).
6404       SmallString<16> CastBuf;
6405       llvm::raw_svector_ostream CastFix(CastBuf);
6406       CastFix << "(";
6407       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6408       CastFix << ")";
6409 
6410       SmallVector<FixItHint,4> Hints;
6411       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6412         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6413 
6414       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6415         // If there's already a cast present, just replace it.
6416         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6417         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6418 
6419       } else if (!requiresParensToAddCast(E)) {
6420         // If the expression has high enough precedence,
6421         // just write the C-style cast.
6422         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6423                                                    CastFix.str()));
6424       } else {
6425         // Otherwise, add parens around the expression as well as the cast.
6426         CastFix << "(";
6427         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6428                                                    CastFix.str()));
6429 
6430         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6431         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6432       }
6433 
6434       if (ShouldNotPrintDirectly) {
6435         // The expression has a type that should not be printed directly.
6436         // We extract the name from the typedef because we don't want to show
6437         // the underlying type in the diagnostic.
6438         StringRef Name;
6439         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6440           Name = TypedefTy->getDecl()->getName();
6441         else
6442           Name = CastTyName;
6443         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6444                                << Name << IntendedTy << IsEnum
6445                                << E->getSourceRange(),
6446                              E->getLocStart(), /*IsStringLocation=*/false,
6447                              SpecRange, Hints);
6448       } else {
6449         // In this case, the expression could be printed using a different
6450         // specifier, but we've decided that the specifier is probably correct
6451         // and we should cast instead. Just use the normal warning message.
6452         EmitFormatDiagnostic(
6453           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6454             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6455             << E->getSourceRange(),
6456           E->getLocStart(), /*IsStringLocation*/false,
6457           SpecRange, Hints);
6458       }
6459     }
6460   } else {
6461     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6462                                                    SpecifierLen);
6463     // Since the warning for passing non-POD types to variadic functions
6464     // was deferred until now, we emit a warning for non-POD
6465     // arguments here.
6466     switch (S.isValidVarArgType(ExprTy)) {
6467     case Sema::VAK_Valid:
6468     case Sema::VAK_ValidInCXX11: {
6469       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6470       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6471         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6472       }
6473 
6474       EmitFormatDiagnostic(
6475           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6476                         << IsEnum << CSR << E->getSourceRange(),
6477           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6478       break;
6479     }
6480     case Sema::VAK_Undefined:
6481     case Sema::VAK_MSVCUndefined:
6482       EmitFormatDiagnostic(
6483         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6484           << S.getLangOpts().CPlusPlus11
6485           << ExprTy
6486           << CallType
6487           << AT.getRepresentativeTypeName(S.Context)
6488           << CSR
6489           << E->getSourceRange(),
6490         E->getLocStart(), /*IsStringLocation*/false, CSR);
6491       checkForCStrMembers(AT, E);
6492       break;
6493 
6494     case Sema::VAK_Invalid:
6495       if (ExprTy->isObjCObjectType())
6496         EmitFormatDiagnostic(
6497           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6498             << S.getLangOpts().CPlusPlus11
6499             << ExprTy
6500             << CallType
6501             << AT.getRepresentativeTypeName(S.Context)
6502             << CSR
6503             << E->getSourceRange(),
6504           E->getLocStart(), /*IsStringLocation*/false, CSR);
6505       else
6506         // FIXME: If this is an initializer list, suggest removing the braces
6507         // or inserting a cast to the target type.
6508         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6509           << isa<InitListExpr>(E) << ExprTy << CallType
6510           << AT.getRepresentativeTypeName(S.Context)
6511           << E->getSourceRange();
6512       break;
6513     }
6514 
6515     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6516            "format string specifier index out of range");
6517     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6518   }
6519 
6520   return true;
6521 }
6522 
6523 //===--- CHECK: Scanf format string checking ------------------------------===//
6524 
6525 namespace {
6526 
6527 class CheckScanfHandler : public CheckFormatHandler {
6528 public:
6529   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6530                     const Expr *origFormatExpr, Sema::FormatStringType type,
6531                     unsigned firstDataArg, unsigned numDataArgs,
6532                     const char *beg, bool hasVAListArg,
6533                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6534                     bool inFunctionCall, Sema::VariadicCallType CallType,
6535                     llvm::SmallBitVector &CheckedVarArgs,
6536                     UncoveredArgHandler &UncoveredArg)
6537       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6538                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6539                            inFunctionCall, CallType, CheckedVarArgs,
6540                            UncoveredArg) {}
6541 
6542   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6543                             const char *startSpecifier,
6544                             unsigned specifierLen) override;
6545 
6546   bool HandleInvalidScanfConversionSpecifier(
6547           const analyze_scanf::ScanfSpecifier &FS,
6548           const char *startSpecifier,
6549           unsigned specifierLen) override;
6550 
6551   void HandleIncompleteScanList(const char *start, const char *end) override;
6552 };
6553 
6554 } // namespace
6555 
6556 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6557                                                  const char *end) {
6558   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6559                        getLocationOfByte(end), /*IsStringLocation*/true,
6560                        getSpecifierRange(start, end - start));
6561 }
6562 
6563 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6564                                         const analyze_scanf::ScanfSpecifier &FS,
6565                                         const char *startSpecifier,
6566                                         unsigned specifierLen) {
6567   const analyze_scanf::ScanfConversionSpecifier &CS =
6568     FS.getConversionSpecifier();
6569 
6570   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6571                                           getLocationOfByte(CS.getStart()),
6572                                           startSpecifier, specifierLen,
6573                                           CS.getStart(), CS.getLength());
6574 }
6575 
6576 bool CheckScanfHandler::HandleScanfSpecifier(
6577                                        const analyze_scanf::ScanfSpecifier &FS,
6578                                        const char *startSpecifier,
6579                                        unsigned specifierLen) {
6580   using namespace analyze_scanf;
6581   using namespace analyze_format_string;
6582 
6583   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6584 
6585   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6586   // be used to decide if we are using positional arguments consistently.
6587   if (FS.consumesDataArgument()) {
6588     if (atFirstArg) {
6589       atFirstArg = false;
6590       usesPositionalArgs = FS.usesPositionalArg();
6591     }
6592     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6593       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6594                                         startSpecifier, specifierLen);
6595       return false;
6596     }
6597   }
6598 
6599   // Check if the field with is non-zero.
6600   const OptionalAmount &Amt = FS.getFieldWidth();
6601   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6602     if (Amt.getConstantAmount() == 0) {
6603       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6604                                                    Amt.getConstantLength());
6605       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6606                            getLocationOfByte(Amt.getStart()),
6607                            /*IsStringLocation*/true, R,
6608                            FixItHint::CreateRemoval(R));
6609     }
6610   }
6611 
6612   if (!FS.consumesDataArgument()) {
6613     // FIXME: Technically specifying a precision or field width here
6614     // makes no sense.  Worth issuing a warning at some point.
6615     return true;
6616   }
6617 
6618   // Consume the argument.
6619   unsigned argIndex = FS.getArgIndex();
6620   if (argIndex < NumDataArgs) {
6621       // The check to see if the argIndex is valid will come later.
6622       // We set the bit here because we may exit early from this
6623       // function if we encounter some other error.
6624     CoveredArgs.set(argIndex);
6625   }
6626 
6627   // Check the length modifier is valid with the given conversion specifier.
6628   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6629     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6630                                 diag::warn_format_nonsensical_length);
6631   else if (!FS.hasStandardLengthModifier())
6632     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6633   else if (!FS.hasStandardLengthConversionCombination())
6634     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6635                                 diag::warn_format_non_standard_conversion_spec);
6636 
6637   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6638     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6639 
6640   // The remaining checks depend on the data arguments.
6641   if (HasVAListArg)
6642     return true;
6643 
6644   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6645     return false;
6646 
6647   // Check that the argument type matches the format specifier.
6648   const Expr *Ex = getDataArg(argIndex);
6649   if (!Ex)
6650     return true;
6651 
6652   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6653 
6654   if (!AT.isValid()) {
6655     return true;
6656   }
6657 
6658   analyze_format_string::ArgType::MatchKind match =
6659       AT.matchesType(S.Context, Ex->getType());
6660   if (match == analyze_format_string::ArgType::Match) {
6661     return true;
6662   }
6663 
6664   ScanfSpecifier fixedFS = FS;
6665   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6666                                  S.getLangOpts(), S.Context);
6667 
6668   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6669   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6670     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6671   }
6672 
6673   if (success) {
6674     // Get the fix string from the fixed format specifier.
6675     SmallString<128> buf;
6676     llvm::raw_svector_ostream os(buf);
6677     fixedFS.toString(os);
6678 
6679     EmitFormatDiagnostic(
6680         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6681                       << Ex->getType() << false << Ex->getSourceRange(),
6682         Ex->getLocStart(),
6683         /*IsStringLocation*/ false,
6684         getSpecifierRange(startSpecifier, specifierLen),
6685         FixItHint::CreateReplacement(
6686             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6687   } else {
6688     EmitFormatDiagnostic(S.PDiag(diag)
6689                              << AT.getRepresentativeTypeName(S.Context)
6690                              << Ex->getType() << false << Ex->getSourceRange(),
6691                          Ex->getLocStart(),
6692                          /*IsStringLocation*/ false,
6693                          getSpecifierRange(startSpecifier, specifierLen));
6694   }
6695 
6696   return true;
6697 }
6698 
6699 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6700                               const Expr *OrigFormatExpr,
6701                               ArrayRef<const Expr *> Args,
6702                               bool HasVAListArg, unsigned format_idx,
6703                               unsigned firstDataArg,
6704                               Sema::FormatStringType Type,
6705                               bool inFunctionCall,
6706                               Sema::VariadicCallType CallType,
6707                               llvm::SmallBitVector &CheckedVarArgs,
6708                               UncoveredArgHandler &UncoveredArg) {
6709   // CHECK: is the format string a wide literal?
6710   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6711     CheckFormatHandler::EmitFormatDiagnostic(
6712       S, inFunctionCall, Args[format_idx],
6713       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6714       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6715     return;
6716   }
6717 
6718   // Str - The format string.  NOTE: this is NOT null-terminated!
6719   StringRef StrRef = FExpr->getString();
6720   const char *Str = StrRef.data();
6721   // Account for cases where the string literal is truncated in a declaration.
6722   const ConstantArrayType *T =
6723     S.Context.getAsConstantArrayType(FExpr->getType());
6724   assert(T && "String literal not of constant array type!");
6725   size_t TypeSize = T->getSize().getZExtValue();
6726   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6727   const unsigned numDataArgs = Args.size() - firstDataArg;
6728 
6729   // Emit a warning if the string literal is truncated and does not contain an
6730   // embedded null character.
6731   if (TypeSize <= StrRef.size() &&
6732       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6733     CheckFormatHandler::EmitFormatDiagnostic(
6734         S, inFunctionCall, Args[format_idx],
6735         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6736         FExpr->getLocStart(),
6737         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6738     return;
6739   }
6740 
6741   // CHECK: empty format string?
6742   if (StrLen == 0 && numDataArgs > 0) {
6743     CheckFormatHandler::EmitFormatDiagnostic(
6744       S, inFunctionCall, Args[format_idx],
6745       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6746       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6747     return;
6748   }
6749 
6750   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6751       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6752       Type == Sema::FST_OSTrace) {
6753     CheckPrintfHandler H(
6754         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6755         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6756         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6757         CheckedVarArgs, UncoveredArg);
6758 
6759     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6760                                                   S.getLangOpts(),
6761                                                   S.Context.getTargetInfo(),
6762                                             Type == Sema::FST_FreeBSDKPrintf))
6763       H.DoneProcessing();
6764   } else if (Type == Sema::FST_Scanf) {
6765     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6766                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6767                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6768 
6769     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6770                                                  S.getLangOpts(),
6771                                                  S.Context.getTargetInfo()))
6772       H.DoneProcessing();
6773   } // TODO: handle other formats
6774 }
6775 
6776 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6777   // Str - The format string.  NOTE: this is NOT null-terminated!
6778   StringRef StrRef = FExpr->getString();
6779   const char *Str = StrRef.data();
6780   // Account for cases where the string literal is truncated in a declaration.
6781   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6782   assert(T && "String literal not of constant array type!");
6783   size_t TypeSize = T->getSize().getZExtValue();
6784   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6785   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6786                                                          getLangOpts(),
6787                                                          Context.getTargetInfo());
6788 }
6789 
6790 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6791 
6792 // Returns the related absolute value function that is larger, of 0 if one
6793 // does not exist.
6794 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6795   switch (AbsFunction) {
6796   default:
6797     return 0;
6798 
6799   case Builtin::BI__builtin_abs:
6800     return Builtin::BI__builtin_labs;
6801   case Builtin::BI__builtin_labs:
6802     return Builtin::BI__builtin_llabs;
6803   case Builtin::BI__builtin_llabs:
6804     return 0;
6805 
6806   case Builtin::BI__builtin_fabsf:
6807     return Builtin::BI__builtin_fabs;
6808   case Builtin::BI__builtin_fabs:
6809     return Builtin::BI__builtin_fabsl;
6810   case Builtin::BI__builtin_fabsl:
6811     return 0;
6812 
6813   case Builtin::BI__builtin_cabsf:
6814     return Builtin::BI__builtin_cabs;
6815   case Builtin::BI__builtin_cabs:
6816     return Builtin::BI__builtin_cabsl;
6817   case Builtin::BI__builtin_cabsl:
6818     return 0;
6819 
6820   case Builtin::BIabs:
6821     return Builtin::BIlabs;
6822   case Builtin::BIlabs:
6823     return Builtin::BIllabs;
6824   case Builtin::BIllabs:
6825     return 0;
6826 
6827   case Builtin::BIfabsf:
6828     return Builtin::BIfabs;
6829   case Builtin::BIfabs:
6830     return Builtin::BIfabsl;
6831   case Builtin::BIfabsl:
6832     return 0;
6833 
6834   case Builtin::BIcabsf:
6835    return Builtin::BIcabs;
6836   case Builtin::BIcabs:
6837     return Builtin::BIcabsl;
6838   case Builtin::BIcabsl:
6839     return 0;
6840   }
6841 }
6842 
6843 // Returns the argument type of the absolute value function.
6844 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6845                                              unsigned AbsType) {
6846   if (AbsType == 0)
6847     return QualType();
6848 
6849   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6850   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6851   if (Error != ASTContext::GE_None)
6852     return QualType();
6853 
6854   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6855   if (!FT)
6856     return QualType();
6857 
6858   if (FT->getNumParams() != 1)
6859     return QualType();
6860 
6861   return FT->getParamType(0);
6862 }
6863 
6864 // Returns the best absolute value function, or zero, based on type and
6865 // current absolute value function.
6866 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6867                                    unsigned AbsFunctionKind) {
6868   unsigned BestKind = 0;
6869   uint64_t ArgSize = Context.getTypeSize(ArgType);
6870   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6871        Kind = getLargerAbsoluteValueFunction(Kind)) {
6872     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6873     if (Context.getTypeSize(ParamType) >= ArgSize) {
6874       if (BestKind == 0)
6875         BestKind = Kind;
6876       else if (Context.hasSameType(ParamType, ArgType)) {
6877         BestKind = Kind;
6878         break;
6879       }
6880     }
6881   }
6882   return BestKind;
6883 }
6884 
6885 enum AbsoluteValueKind {
6886   AVK_Integer,
6887   AVK_Floating,
6888   AVK_Complex
6889 };
6890 
6891 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6892   if (T->isIntegralOrEnumerationType())
6893     return AVK_Integer;
6894   if (T->isRealFloatingType())
6895     return AVK_Floating;
6896   if (T->isAnyComplexType())
6897     return AVK_Complex;
6898 
6899   llvm_unreachable("Type not integer, floating, or complex");
6900 }
6901 
6902 // Changes the absolute value function to a different type.  Preserves whether
6903 // the function is a builtin.
6904 static unsigned changeAbsFunction(unsigned AbsKind,
6905                                   AbsoluteValueKind ValueKind) {
6906   switch (ValueKind) {
6907   case AVK_Integer:
6908     switch (AbsKind) {
6909     default:
6910       return 0;
6911     case Builtin::BI__builtin_fabsf:
6912     case Builtin::BI__builtin_fabs:
6913     case Builtin::BI__builtin_fabsl:
6914     case Builtin::BI__builtin_cabsf:
6915     case Builtin::BI__builtin_cabs:
6916     case Builtin::BI__builtin_cabsl:
6917       return Builtin::BI__builtin_abs;
6918     case Builtin::BIfabsf:
6919     case Builtin::BIfabs:
6920     case Builtin::BIfabsl:
6921     case Builtin::BIcabsf:
6922     case Builtin::BIcabs:
6923     case Builtin::BIcabsl:
6924       return Builtin::BIabs;
6925     }
6926   case AVK_Floating:
6927     switch (AbsKind) {
6928     default:
6929       return 0;
6930     case Builtin::BI__builtin_abs:
6931     case Builtin::BI__builtin_labs:
6932     case Builtin::BI__builtin_llabs:
6933     case Builtin::BI__builtin_cabsf:
6934     case Builtin::BI__builtin_cabs:
6935     case Builtin::BI__builtin_cabsl:
6936       return Builtin::BI__builtin_fabsf;
6937     case Builtin::BIabs:
6938     case Builtin::BIlabs:
6939     case Builtin::BIllabs:
6940     case Builtin::BIcabsf:
6941     case Builtin::BIcabs:
6942     case Builtin::BIcabsl:
6943       return Builtin::BIfabsf;
6944     }
6945   case AVK_Complex:
6946     switch (AbsKind) {
6947     default:
6948       return 0;
6949     case Builtin::BI__builtin_abs:
6950     case Builtin::BI__builtin_labs:
6951     case Builtin::BI__builtin_llabs:
6952     case Builtin::BI__builtin_fabsf:
6953     case Builtin::BI__builtin_fabs:
6954     case Builtin::BI__builtin_fabsl:
6955       return Builtin::BI__builtin_cabsf;
6956     case Builtin::BIabs:
6957     case Builtin::BIlabs:
6958     case Builtin::BIllabs:
6959     case Builtin::BIfabsf:
6960     case Builtin::BIfabs:
6961     case Builtin::BIfabsl:
6962       return Builtin::BIcabsf;
6963     }
6964   }
6965   llvm_unreachable("Unable to convert function");
6966 }
6967 
6968 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6969   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6970   if (!FnInfo)
6971     return 0;
6972 
6973   switch (FDecl->getBuiltinID()) {
6974   default:
6975     return 0;
6976   case Builtin::BI__builtin_abs:
6977   case Builtin::BI__builtin_fabs:
6978   case Builtin::BI__builtin_fabsf:
6979   case Builtin::BI__builtin_fabsl:
6980   case Builtin::BI__builtin_labs:
6981   case Builtin::BI__builtin_llabs:
6982   case Builtin::BI__builtin_cabs:
6983   case Builtin::BI__builtin_cabsf:
6984   case Builtin::BI__builtin_cabsl:
6985   case Builtin::BIabs:
6986   case Builtin::BIlabs:
6987   case Builtin::BIllabs:
6988   case Builtin::BIfabs:
6989   case Builtin::BIfabsf:
6990   case Builtin::BIfabsl:
6991   case Builtin::BIcabs:
6992   case Builtin::BIcabsf:
6993   case Builtin::BIcabsl:
6994     return FDecl->getBuiltinID();
6995   }
6996   llvm_unreachable("Unknown Builtin type");
6997 }
6998 
6999 // If the replacement is valid, emit a note with replacement function.
7000 // Additionally, suggest including the proper header if not already included.
7001 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
7002                             unsigned AbsKind, QualType ArgType) {
7003   bool EmitHeaderHint = true;
7004   const char *HeaderName = nullptr;
7005   const char *FunctionName = nullptr;
7006   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7007     FunctionName = "std::abs";
7008     if (ArgType->isIntegralOrEnumerationType()) {
7009       HeaderName = "cstdlib";
7010     } else if (ArgType->isRealFloatingType()) {
7011       HeaderName = "cmath";
7012     } else {
7013       llvm_unreachable("Invalid Type");
7014     }
7015 
7016     // Lookup all std::abs
7017     if (NamespaceDecl *Std = S.getStdNamespace()) {
7018       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
7019       R.suppressDiagnostics();
7020       S.LookupQualifiedName(R, Std);
7021 
7022       for (const auto *I : R) {
7023         const FunctionDecl *FDecl = nullptr;
7024         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7025           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7026         } else {
7027           FDecl = dyn_cast<FunctionDecl>(I);
7028         }
7029         if (!FDecl)
7030           continue;
7031 
7032         // Found std::abs(), check that they are the right ones.
7033         if (FDecl->getNumParams() != 1)
7034           continue;
7035 
7036         // Check that the parameter type can handle the argument.
7037         QualType ParamType = FDecl->getParamDecl(0)->getType();
7038         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7039             S.Context.getTypeSize(ArgType) <=
7040                 S.Context.getTypeSize(ParamType)) {
7041           // Found a function, don't need the header hint.
7042           EmitHeaderHint = false;
7043           break;
7044         }
7045       }
7046     }
7047   } else {
7048     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
7049     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7050 
7051     if (HeaderName) {
7052       DeclarationName DN(&S.Context.Idents.get(FunctionName));
7053       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7054       R.suppressDiagnostics();
7055       S.LookupName(R, S.getCurScope());
7056 
7057       if (R.isSingleResult()) {
7058         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7059         if (FD && FD->getBuiltinID() == AbsKind) {
7060           EmitHeaderHint = false;
7061         } else {
7062           return;
7063         }
7064       } else if (!R.empty()) {
7065         return;
7066       }
7067     }
7068   }
7069 
7070   S.Diag(Loc, diag::note_replace_abs_function)
7071       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7072 
7073   if (!HeaderName)
7074     return;
7075 
7076   if (!EmitHeaderHint)
7077     return;
7078 
7079   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7080                                                     << FunctionName;
7081 }
7082 
7083 template <std::size_t StrLen>
7084 static bool IsStdFunction(const FunctionDecl *FDecl,
7085                           const char (&Str)[StrLen]) {
7086   if (!FDecl)
7087     return false;
7088   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7089     return false;
7090   if (!FDecl->isInStdNamespace())
7091     return false;
7092 
7093   return true;
7094 }
7095 
7096 // Warn when using the wrong abs() function.
7097 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7098                                       const FunctionDecl *FDecl) {
7099   if (Call->getNumArgs() != 1)
7100     return;
7101 
7102   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7103   bool IsStdAbs = IsStdFunction(FDecl, "abs");
7104   if (AbsKind == 0 && !IsStdAbs)
7105     return;
7106 
7107   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7108   QualType ParamType = Call->getArg(0)->getType();
7109 
7110   // Unsigned types cannot be negative.  Suggest removing the absolute value
7111   // function call.
7112   if (ArgType->isUnsignedIntegerType()) {
7113     const char *FunctionName =
7114         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7115     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7116     Diag(Call->getExprLoc(), diag::note_remove_abs)
7117         << FunctionName
7118         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7119     return;
7120   }
7121 
7122   // Taking the absolute value of a pointer is very suspicious, they probably
7123   // wanted to index into an array, dereference a pointer, call a function, etc.
7124   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7125     unsigned DiagType = 0;
7126     if (ArgType->isFunctionType())
7127       DiagType = 1;
7128     else if (ArgType->isArrayType())
7129       DiagType = 2;
7130 
7131     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7132     return;
7133   }
7134 
7135   // std::abs has overloads which prevent most of the absolute value problems
7136   // from occurring.
7137   if (IsStdAbs)
7138     return;
7139 
7140   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7141   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7142 
7143   // The argument and parameter are the same kind.  Check if they are the right
7144   // size.
7145   if (ArgValueKind == ParamValueKind) {
7146     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7147       return;
7148 
7149     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7150     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7151         << FDecl << ArgType << ParamType;
7152 
7153     if (NewAbsKind == 0)
7154       return;
7155 
7156     emitReplacement(*this, Call->getExprLoc(),
7157                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7158     return;
7159   }
7160 
7161   // ArgValueKind != ParamValueKind
7162   // The wrong type of absolute value function was used.  Attempt to find the
7163   // proper one.
7164   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7165   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7166   if (NewAbsKind == 0)
7167     return;
7168 
7169   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7170       << FDecl << ParamValueKind << ArgValueKind;
7171 
7172   emitReplacement(*this, Call->getExprLoc(),
7173                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7174 }
7175 
7176 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7177 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7178                                 const FunctionDecl *FDecl) {
7179   if (!Call || !FDecl) return;
7180 
7181   // Ignore template specializations and macros.
7182   if (inTemplateInstantiation()) return;
7183   if (Call->getExprLoc().isMacroID()) return;
7184 
7185   // Only care about the one template argument, two function parameter std::max
7186   if (Call->getNumArgs() != 2) return;
7187   if (!IsStdFunction(FDecl, "max")) return;
7188   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7189   if (!ArgList) return;
7190   if (ArgList->size() != 1) return;
7191 
7192   // Check that template type argument is unsigned integer.
7193   const auto& TA = ArgList->get(0);
7194   if (TA.getKind() != TemplateArgument::Type) return;
7195   QualType ArgType = TA.getAsType();
7196   if (!ArgType->isUnsignedIntegerType()) return;
7197 
7198   // See if either argument is a literal zero.
7199   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7200     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7201     if (!MTE) return false;
7202     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7203     if (!Num) return false;
7204     if (Num->getValue() != 0) return false;
7205     return true;
7206   };
7207 
7208   const Expr *FirstArg = Call->getArg(0);
7209   const Expr *SecondArg = Call->getArg(1);
7210   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7211   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7212 
7213   // Only warn when exactly one argument is zero.
7214   if (IsFirstArgZero == IsSecondArgZero) return;
7215 
7216   SourceRange FirstRange = FirstArg->getSourceRange();
7217   SourceRange SecondRange = SecondArg->getSourceRange();
7218 
7219   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7220 
7221   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7222       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7223 
7224   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7225   SourceRange RemovalRange;
7226   if (IsFirstArgZero) {
7227     RemovalRange = SourceRange(FirstRange.getBegin(),
7228                                SecondRange.getBegin().getLocWithOffset(-1));
7229   } else {
7230     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7231                                SecondRange.getEnd());
7232   }
7233 
7234   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7235         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7236         << FixItHint::CreateRemoval(RemovalRange);
7237 }
7238 
7239 //===--- CHECK: Standard memory functions ---------------------------------===//
7240 
7241 /// \brief Takes the expression passed to the size_t parameter of functions
7242 /// such as memcmp, strncat, etc and warns if it's a comparison.
7243 ///
7244 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7245 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7246                                            IdentifierInfo *FnName,
7247                                            SourceLocation FnLoc,
7248                                            SourceLocation RParenLoc) {
7249   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7250   if (!Size)
7251     return false;
7252 
7253   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7254   if (!Size->isComparisonOp() && !Size->isLogicalOp())
7255     return false;
7256 
7257   SourceRange SizeRange = Size->getSourceRange();
7258   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7259       << SizeRange << FnName;
7260   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7261       << FnName << FixItHint::CreateInsertion(
7262                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7263       << FixItHint::CreateRemoval(RParenLoc);
7264   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7265       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7266       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7267                                     ")");
7268 
7269   return true;
7270 }
7271 
7272 /// \brief Determine whether the given type is or contains a dynamic class type
7273 /// (e.g., whether it has a vtable).
7274 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7275                                                      bool &IsContained) {
7276   // Look through array types while ignoring qualifiers.
7277   const Type *Ty = T->getBaseElementTypeUnsafe();
7278   IsContained = false;
7279 
7280   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7281   RD = RD ? RD->getDefinition() : nullptr;
7282   if (!RD || RD->isInvalidDecl())
7283     return nullptr;
7284 
7285   if (RD->isDynamicClass())
7286     return RD;
7287 
7288   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7289   // It's impossible for a class to transitively contain itself by value, so
7290   // infinite recursion is impossible.
7291   for (auto *FD : RD->fields()) {
7292     bool SubContained;
7293     if (const CXXRecordDecl *ContainedRD =
7294             getContainedDynamicClass(FD->getType(), SubContained)) {
7295       IsContained = true;
7296       return ContainedRD;
7297     }
7298   }
7299 
7300   return nullptr;
7301 }
7302 
7303 /// \brief If E is a sizeof expression, returns its argument expression,
7304 /// otherwise returns NULL.
7305 static const Expr *getSizeOfExprArg(const Expr *E) {
7306   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7307       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7308     if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
7309       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7310 
7311   return nullptr;
7312 }
7313 
7314 /// \brief If E is a sizeof expression, returns its argument type.
7315 static QualType getSizeOfArgType(const Expr *E) {
7316   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7317       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7318     if (SizeOf->getKind() == UETT_SizeOf)
7319       return SizeOf->getTypeOfArgument();
7320 
7321   return QualType();
7322 }
7323 
7324 /// \brief Check for dangerous or invalid arguments to memset().
7325 ///
7326 /// This issues warnings on known problematic, dangerous or unspecified
7327 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7328 /// function calls.
7329 ///
7330 /// \param Call The call expression to diagnose.
7331 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7332                                    unsigned BId,
7333                                    IdentifierInfo *FnName) {
7334   assert(BId != 0);
7335 
7336   // It is possible to have a non-standard definition of memset.  Validate
7337   // we have enough arguments, and if not, abort further checking.
7338   unsigned ExpectedNumArgs =
7339       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7340   if (Call->getNumArgs() < ExpectedNumArgs)
7341     return;
7342 
7343   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7344                       BId == Builtin::BIstrndup ? 1 : 2);
7345   unsigned LenArg =
7346       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7347   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7348 
7349   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7350                                      Call->getLocStart(), Call->getRParenLoc()))
7351     return;
7352 
7353   // We have special checking when the length is a sizeof expression.
7354   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7355   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7356   llvm::FoldingSetNodeID SizeOfArgID;
7357 
7358   // Although widely used, 'bzero' is not a standard function. Be more strict
7359   // with the argument types before allowing diagnostics and only allow the
7360   // form bzero(ptr, sizeof(...)).
7361   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7362   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7363     return;
7364 
7365   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7366     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7367     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7368 
7369     QualType DestTy = Dest->getType();
7370     QualType PointeeTy;
7371     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7372       PointeeTy = DestPtrTy->getPointeeType();
7373 
7374       // Never warn about void type pointers. This can be used to suppress
7375       // false positives.
7376       if (PointeeTy->isVoidType())
7377         continue;
7378 
7379       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7380       // actually comparing the expressions for equality. Because computing the
7381       // expression IDs can be expensive, we only do this if the diagnostic is
7382       // enabled.
7383       if (SizeOfArg &&
7384           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7385                            SizeOfArg->getExprLoc())) {
7386         // We only compute IDs for expressions if the warning is enabled, and
7387         // cache the sizeof arg's ID.
7388         if (SizeOfArgID == llvm::FoldingSetNodeID())
7389           SizeOfArg->Profile(SizeOfArgID, Context, true);
7390         llvm::FoldingSetNodeID DestID;
7391         Dest->Profile(DestID, Context, true);
7392         if (DestID == SizeOfArgID) {
7393           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7394           //       over sizeof(src) as well.
7395           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7396           StringRef ReadableName = FnName->getName();
7397 
7398           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7399             if (UnaryOp->getOpcode() == UO_AddrOf)
7400               ActionIdx = 1; // If its an address-of operator, just remove it.
7401           if (!PointeeTy->isIncompleteType() &&
7402               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7403             ActionIdx = 2; // If the pointee's size is sizeof(char),
7404                            // suggest an explicit length.
7405 
7406           // If the function is defined as a builtin macro, do not show macro
7407           // expansion.
7408           SourceLocation SL = SizeOfArg->getExprLoc();
7409           SourceRange DSR = Dest->getSourceRange();
7410           SourceRange SSR = SizeOfArg->getSourceRange();
7411           SourceManager &SM = getSourceManager();
7412 
7413           if (SM.isMacroArgExpansion(SL)) {
7414             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7415             SL = SM.getSpellingLoc(SL);
7416             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7417                              SM.getSpellingLoc(DSR.getEnd()));
7418             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7419                              SM.getSpellingLoc(SSR.getEnd()));
7420           }
7421 
7422           DiagRuntimeBehavior(SL, SizeOfArg,
7423                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7424                                 << ReadableName
7425                                 << PointeeTy
7426                                 << DestTy
7427                                 << DSR
7428                                 << SSR);
7429           DiagRuntimeBehavior(SL, SizeOfArg,
7430                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7431                                 << ActionIdx
7432                                 << SSR);
7433 
7434           break;
7435         }
7436       }
7437 
7438       // Also check for cases where the sizeof argument is the exact same
7439       // type as the memory argument, and where it points to a user-defined
7440       // record type.
7441       if (SizeOfArgTy != QualType()) {
7442         if (PointeeTy->isRecordType() &&
7443             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7444           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7445                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7446                                 << FnName << SizeOfArgTy << ArgIdx
7447                                 << PointeeTy << Dest->getSourceRange()
7448                                 << LenExpr->getSourceRange());
7449           break;
7450         }
7451       }
7452     } else if (DestTy->isArrayType()) {
7453       PointeeTy = DestTy;
7454     }
7455 
7456     if (PointeeTy == QualType())
7457       continue;
7458 
7459     // Always complain about dynamic classes.
7460     bool IsContained;
7461     if (const CXXRecordDecl *ContainedRD =
7462             getContainedDynamicClass(PointeeTy, IsContained)) {
7463 
7464       unsigned OperationType = 0;
7465       // "overwritten" if we're warning about the destination for any call
7466       // but memcmp; otherwise a verb appropriate to the call.
7467       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7468         if (BId == Builtin::BImemcpy)
7469           OperationType = 1;
7470         else if(BId == Builtin::BImemmove)
7471           OperationType = 2;
7472         else if (BId == Builtin::BImemcmp)
7473           OperationType = 3;
7474       }
7475 
7476       DiagRuntimeBehavior(
7477         Dest->getExprLoc(), Dest,
7478         PDiag(diag::warn_dyn_class_memaccess)
7479           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7480           << FnName << IsContained << ContainedRD << OperationType
7481           << Call->getCallee()->getSourceRange());
7482     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7483              BId != Builtin::BImemset)
7484       DiagRuntimeBehavior(
7485         Dest->getExprLoc(), Dest,
7486         PDiag(diag::warn_arc_object_memaccess)
7487           << ArgIdx << FnName << PointeeTy
7488           << Call->getCallee()->getSourceRange());
7489     else
7490       continue;
7491 
7492     DiagRuntimeBehavior(
7493       Dest->getExprLoc(), Dest,
7494       PDiag(diag::note_bad_memaccess_silence)
7495         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7496     break;
7497   }
7498 }
7499 
7500 // A little helper routine: ignore addition and subtraction of integer literals.
7501 // This intentionally does not ignore all integer constant expressions because
7502 // we don't want to remove sizeof().
7503 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7504   Ex = Ex->IgnoreParenCasts();
7505 
7506   while (true) {
7507     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7508     if (!BO || !BO->isAdditiveOp())
7509       break;
7510 
7511     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7512     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7513 
7514     if (isa<IntegerLiteral>(RHS))
7515       Ex = LHS;
7516     else if (isa<IntegerLiteral>(LHS))
7517       Ex = RHS;
7518     else
7519       break;
7520   }
7521 
7522   return Ex;
7523 }
7524 
7525 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7526                                                       ASTContext &Context) {
7527   // Only handle constant-sized or VLAs, but not flexible members.
7528   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7529     // Only issue the FIXIT for arrays of size > 1.
7530     if (CAT->getSize().getSExtValue() <= 1)
7531       return false;
7532   } else if (!Ty->isVariableArrayType()) {
7533     return false;
7534   }
7535   return true;
7536 }
7537 
7538 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7539 // be the size of the source, instead of the destination.
7540 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7541                                     IdentifierInfo *FnName) {
7542 
7543   // Don't crash if the user has the wrong number of arguments
7544   unsigned NumArgs = Call->getNumArgs();
7545   if ((NumArgs != 3) && (NumArgs != 4))
7546     return;
7547 
7548   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7549   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7550   const Expr *CompareWithSrc = nullptr;
7551 
7552   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7553                                      Call->getLocStart(), Call->getRParenLoc()))
7554     return;
7555 
7556   // Look for 'strlcpy(dst, x, sizeof(x))'
7557   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7558     CompareWithSrc = Ex;
7559   else {
7560     // Look for 'strlcpy(dst, x, strlen(x))'
7561     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7562       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7563           SizeCall->getNumArgs() == 1)
7564         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7565     }
7566   }
7567 
7568   if (!CompareWithSrc)
7569     return;
7570 
7571   // Determine if the argument to sizeof/strlen is equal to the source
7572   // argument.  In principle there's all kinds of things you could do
7573   // here, for instance creating an == expression and evaluating it with
7574   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7575   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7576   if (!SrcArgDRE)
7577     return;
7578 
7579   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7580   if (!CompareWithSrcDRE ||
7581       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7582     return;
7583 
7584   const Expr *OriginalSizeArg = Call->getArg(2);
7585   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7586     << OriginalSizeArg->getSourceRange() << FnName;
7587 
7588   // Output a FIXIT hint if the destination is an array (rather than a
7589   // pointer to an array).  This could be enhanced to handle some
7590   // pointers if we know the actual size, like if DstArg is 'array+2'
7591   // we could say 'sizeof(array)-2'.
7592   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7593   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7594     return;
7595 
7596   SmallString<128> sizeString;
7597   llvm::raw_svector_ostream OS(sizeString);
7598   OS << "sizeof(";
7599   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7600   OS << ")";
7601 
7602   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7603     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7604                                     OS.str());
7605 }
7606 
7607 /// Check if two expressions refer to the same declaration.
7608 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7609   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7610     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7611       return D1->getDecl() == D2->getDecl();
7612   return false;
7613 }
7614 
7615 static const Expr *getStrlenExprArg(const Expr *E) {
7616   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7617     const FunctionDecl *FD = CE->getDirectCallee();
7618     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7619       return nullptr;
7620     return CE->getArg(0)->IgnoreParenCasts();
7621   }
7622   return nullptr;
7623 }
7624 
7625 // Warn on anti-patterns as the 'size' argument to strncat.
7626 // The correct size argument should look like following:
7627 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7628 void Sema::CheckStrncatArguments(const CallExpr *CE,
7629                                  IdentifierInfo *FnName) {
7630   // Don't crash if the user has the wrong number of arguments.
7631   if (CE->getNumArgs() < 3)
7632     return;
7633   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7634   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7635   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7636 
7637   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7638                                      CE->getRParenLoc()))
7639     return;
7640 
7641   // Identify common expressions, which are wrongly used as the size argument
7642   // to strncat and may lead to buffer overflows.
7643   unsigned PatternType = 0;
7644   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7645     // - sizeof(dst)
7646     if (referToTheSameDecl(SizeOfArg, DstArg))
7647       PatternType = 1;
7648     // - sizeof(src)
7649     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7650       PatternType = 2;
7651   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7652     if (BE->getOpcode() == BO_Sub) {
7653       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7654       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7655       // - sizeof(dst) - strlen(dst)
7656       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7657           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7658         PatternType = 1;
7659       // - sizeof(src) - (anything)
7660       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7661         PatternType = 2;
7662     }
7663   }
7664 
7665   if (PatternType == 0)
7666     return;
7667 
7668   // Generate the diagnostic.
7669   SourceLocation SL = LenArg->getLocStart();
7670   SourceRange SR = LenArg->getSourceRange();
7671   SourceManager &SM = getSourceManager();
7672 
7673   // If the function is defined as a builtin macro, do not show macro expansion.
7674   if (SM.isMacroArgExpansion(SL)) {
7675     SL = SM.getSpellingLoc(SL);
7676     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7677                      SM.getSpellingLoc(SR.getEnd()));
7678   }
7679 
7680   // Check if the destination is an array (rather than a pointer to an array).
7681   QualType DstTy = DstArg->getType();
7682   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7683                                                                     Context);
7684   if (!isKnownSizeArray) {
7685     if (PatternType == 1)
7686       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7687     else
7688       Diag(SL, diag::warn_strncat_src_size) << SR;
7689     return;
7690   }
7691 
7692   if (PatternType == 1)
7693     Diag(SL, diag::warn_strncat_large_size) << SR;
7694   else
7695     Diag(SL, diag::warn_strncat_src_size) << SR;
7696 
7697   SmallString<128> sizeString;
7698   llvm::raw_svector_ostream OS(sizeString);
7699   OS << "sizeof(";
7700   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7701   OS << ") - ";
7702   OS << "strlen(";
7703   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7704   OS << ") - 1";
7705 
7706   Diag(SL, diag::note_strncat_wrong_size)
7707     << FixItHint::CreateReplacement(SR, OS.str());
7708 }
7709 
7710 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7711 
7712 static const Expr *EvalVal(const Expr *E,
7713                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7714                            const Decl *ParentDecl);
7715 static const Expr *EvalAddr(const Expr *E,
7716                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7717                             const Decl *ParentDecl);
7718 
7719 /// CheckReturnStackAddr - Check if a return statement returns the address
7720 ///   of a stack variable.
7721 static void
7722 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7723                      SourceLocation ReturnLoc) {
7724   const Expr *stackE = nullptr;
7725   SmallVector<const DeclRefExpr *, 8> refVars;
7726 
7727   // Perform checking for returned stack addresses, local blocks,
7728   // label addresses or references to temporaries.
7729   if (lhsType->isPointerType() ||
7730       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7731     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7732   } else if (lhsType->isReferenceType()) {
7733     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7734   }
7735 
7736   if (!stackE)
7737     return; // Nothing suspicious was found.
7738 
7739   // Parameters are initialized in the calling scope, so taking the address
7740   // of a parameter reference doesn't need a warning.
7741   for (auto *DRE : refVars)
7742     if (isa<ParmVarDecl>(DRE->getDecl()))
7743       return;
7744 
7745   SourceLocation diagLoc;
7746   SourceRange diagRange;
7747   if (refVars.empty()) {
7748     diagLoc = stackE->getLocStart();
7749     diagRange = stackE->getSourceRange();
7750   } else {
7751     // We followed through a reference variable. 'stackE' contains the
7752     // problematic expression but we will warn at the return statement pointing
7753     // at the reference variable. We will later display the "trail" of
7754     // reference variables using notes.
7755     diagLoc = refVars[0]->getLocStart();
7756     diagRange = refVars[0]->getSourceRange();
7757   }
7758 
7759   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7760     // address of local var
7761     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7762      << DR->getDecl()->getDeclName() << diagRange;
7763   } else if (isa<BlockExpr>(stackE)) { // local block.
7764     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7765   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7766     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7767   } else { // local temporary.
7768     // If there is an LValue->RValue conversion, then the value of the
7769     // reference type is used, not the reference.
7770     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7771       if (ICE->getCastKind() == CK_LValueToRValue) {
7772         return;
7773       }
7774     }
7775     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7776      << lhsType->isReferenceType() << diagRange;
7777   }
7778 
7779   // Display the "trail" of reference variables that we followed until we
7780   // found the problematic expression using notes.
7781   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7782     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7783     // If this var binds to another reference var, show the range of the next
7784     // var, otherwise the var binds to the problematic expression, in which case
7785     // show the range of the expression.
7786     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7787                                     : stackE->getSourceRange();
7788     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7789         << VD->getDeclName() << range;
7790   }
7791 }
7792 
7793 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7794 ///  check if the expression in a return statement evaluates to an address
7795 ///  to a location on the stack, a local block, an address of a label, or a
7796 ///  reference to local temporary. The recursion is used to traverse the
7797 ///  AST of the return expression, with recursion backtracking when we
7798 ///  encounter a subexpression that (1) clearly does not lead to one of the
7799 ///  above problematic expressions (2) is something we cannot determine leads to
7800 ///  a problematic expression based on such local checking.
7801 ///
7802 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7803 ///  the expression that they point to. Such variables are added to the
7804 ///  'refVars' vector so that we know what the reference variable "trail" was.
7805 ///
7806 ///  EvalAddr processes expressions that are pointers that are used as
7807 ///  references (and not L-values).  EvalVal handles all other values.
7808 ///  At the base case of the recursion is a check for the above problematic
7809 ///  expressions.
7810 ///
7811 ///  This implementation handles:
7812 ///
7813 ///   * pointer-to-pointer casts
7814 ///   * implicit conversions from array references to pointers
7815 ///   * taking the address of fields
7816 ///   * arbitrary interplay between "&" and "*" operators
7817 ///   * pointer arithmetic from an address of a stack variable
7818 ///   * taking the address of an array element where the array is on the stack
7819 static const Expr *EvalAddr(const Expr *E,
7820                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7821                             const Decl *ParentDecl) {
7822   if (E->isTypeDependent())
7823     return nullptr;
7824 
7825   // We should only be called for evaluating pointer expressions.
7826   assert((E->getType()->isAnyPointerType() ||
7827           E->getType()->isBlockPointerType() ||
7828           E->getType()->isObjCQualifiedIdType()) &&
7829          "EvalAddr only works on pointers");
7830 
7831   E = E->IgnoreParens();
7832 
7833   // Our "symbolic interpreter" is just a dispatch off the currently
7834   // viewed AST node.  We then recursively traverse the AST by calling
7835   // EvalAddr and EvalVal appropriately.
7836   switch (E->getStmtClass()) {
7837   case Stmt::DeclRefExprClass: {
7838     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7839 
7840     // If we leave the immediate function, the lifetime isn't about to end.
7841     if (DR->refersToEnclosingVariableOrCapture())
7842       return nullptr;
7843 
7844     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7845       // If this is a reference variable, follow through to the expression that
7846       // it points to.
7847       if (V->hasLocalStorage() &&
7848           V->getType()->isReferenceType() && V->hasInit()) {
7849         // Add the reference variable to the "trail".
7850         refVars.push_back(DR);
7851         return EvalAddr(V->getInit(), refVars, ParentDecl);
7852       }
7853 
7854     return nullptr;
7855   }
7856 
7857   case Stmt::UnaryOperatorClass: {
7858     // The only unary operator that make sense to handle here
7859     // is AddrOf.  All others don't make sense as pointers.
7860     const UnaryOperator *U = cast<UnaryOperator>(E);
7861 
7862     if (U->getOpcode() == UO_AddrOf)
7863       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7864     return nullptr;
7865   }
7866 
7867   case Stmt::BinaryOperatorClass: {
7868     // Handle pointer arithmetic.  All other binary operators are not valid
7869     // in this context.
7870     const BinaryOperator *B = cast<BinaryOperator>(E);
7871     BinaryOperatorKind op = B->getOpcode();
7872 
7873     if (op != BO_Add && op != BO_Sub)
7874       return nullptr;
7875 
7876     const Expr *Base = B->getLHS();
7877 
7878     // Determine which argument is the real pointer base.  It could be
7879     // the RHS argument instead of the LHS.
7880     if (!Base->getType()->isPointerType())
7881       Base = B->getRHS();
7882 
7883     assert(Base->getType()->isPointerType());
7884     return EvalAddr(Base, refVars, ParentDecl);
7885   }
7886 
7887   // For conditional operators we need to see if either the LHS or RHS are
7888   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7889   case Stmt::ConditionalOperatorClass: {
7890     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7891 
7892     // Handle the GNU extension for missing LHS.
7893     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7894     if (const Expr *LHSExpr = C->getLHS()) {
7895       // In C++, we can have a throw-expression, which has 'void' type.
7896       if (!LHSExpr->getType()->isVoidType())
7897         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7898           return LHS;
7899     }
7900 
7901     // In C++, we can have a throw-expression, which has 'void' type.
7902     if (C->getRHS()->getType()->isVoidType())
7903       return nullptr;
7904 
7905     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7906   }
7907 
7908   case Stmt::BlockExprClass:
7909     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7910       return E; // local block.
7911     return nullptr;
7912 
7913   case Stmt::AddrLabelExprClass:
7914     return E; // address of label.
7915 
7916   case Stmt::ExprWithCleanupsClass:
7917     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7918                     ParentDecl);
7919 
7920   // For casts, we need to handle conversions from arrays to
7921   // pointer values, and pointer-to-pointer conversions.
7922   case Stmt::ImplicitCastExprClass:
7923   case Stmt::CStyleCastExprClass:
7924   case Stmt::CXXFunctionalCastExprClass:
7925   case Stmt::ObjCBridgedCastExprClass:
7926   case Stmt::CXXStaticCastExprClass:
7927   case Stmt::CXXDynamicCastExprClass:
7928   case Stmt::CXXConstCastExprClass:
7929   case Stmt::CXXReinterpretCastExprClass: {
7930     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7931     switch (cast<CastExpr>(E)->getCastKind()) {
7932     case CK_LValueToRValue:
7933     case CK_NoOp:
7934     case CK_BaseToDerived:
7935     case CK_DerivedToBase:
7936     case CK_UncheckedDerivedToBase:
7937     case CK_Dynamic:
7938     case CK_CPointerToObjCPointerCast:
7939     case CK_BlockPointerToObjCPointerCast:
7940     case CK_AnyPointerToBlockPointerCast:
7941       return EvalAddr(SubExpr, refVars, ParentDecl);
7942 
7943     case CK_ArrayToPointerDecay:
7944       return EvalVal(SubExpr, refVars, ParentDecl);
7945 
7946     case CK_BitCast:
7947       if (SubExpr->getType()->isAnyPointerType() ||
7948           SubExpr->getType()->isBlockPointerType() ||
7949           SubExpr->getType()->isObjCQualifiedIdType())
7950         return EvalAddr(SubExpr, refVars, ParentDecl);
7951       else
7952         return nullptr;
7953 
7954     default:
7955       return nullptr;
7956     }
7957   }
7958 
7959   case Stmt::MaterializeTemporaryExprClass:
7960     if (const Expr *Result =
7961             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7962                      refVars, ParentDecl))
7963       return Result;
7964     return E;
7965 
7966   // Everything else: we simply don't reason about them.
7967   default:
7968     return nullptr;
7969   }
7970 }
7971 
7972 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7973 ///   See the comments for EvalAddr for more details.
7974 static const Expr *EvalVal(const Expr *E,
7975                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7976                            const Decl *ParentDecl) {
7977   do {
7978     // We should only be called for evaluating non-pointer expressions, or
7979     // expressions with a pointer type that are not used as references but
7980     // instead
7981     // are l-values (e.g., DeclRefExpr with a pointer type).
7982 
7983     // Our "symbolic interpreter" is just a dispatch off the currently
7984     // viewed AST node.  We then recursively traverse the AST by calling
7985     // EvalAddr and EvalVal appropriately.
7986 
7987     E = E->IgnoreParens();
7988     switch (E->getStmtClass()) {
7989     case Stmt::ImplicitCastExprClass: {
7990       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7991       if (IE->getValueKind() == VK_LValue) {
7992         E = IE->getSubExpr();
7993         continue;
7994       }
7995       return nullptr;
7996     }
7997 
7998     case Stmt::ExprWithCleanupsClass:
7999       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8000                      ParentDecl);
8001 
8002     case Stmt::DeclRefExprClass: {
8003       // When we hit a DeclRefExpr we are looking at code that refers to a
8004       // variable's name. If it's not a reference variable we check if it has
8005       // local storage within the function, and if so, return the expression.
8006       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8007 
8008       // If we leave the immediate function, the lifetime isn't about to end.
8009       if (DR->refersToEnclosingVariableOrCapture())
8010         return nullptr;
8011 
8012       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8013         // Check if it refers to itself, e.g. "int& i = i;".
8014         if (V == ParentDecl)
8015           return DR;
8016 
8017         if (V->hasLocalStorage()) {
8018           if (!V->getType()->isReferenceType())
8019             return DR;
8020 
8021           // Reference variable, follow through to the expression that
8022           // it points to.
8023           if (V->hasInit()) {
8024             // Add the reference variable to the "trail".
8025             refVars.push_back(DR);
8026             return EvalVal(V->getInit(), refVars, V);
8027           }
8028         }
8029       }
8030 
8031       return nullptr;
8032     }
8033 
8034     case Stmt::UnaryOperatorClass: {
8035       // The only unary operator that make sense to handle here
8036       // is Deref.  All others don't resolve to a "name."  This includes
8037       // handling all sorts of rvalues passed to a unary operator.
8038       const UnaryOperator *U = cast<UnaryOperator>(E);
8039 
8040       if (U->getOpcode() == UO_Deref)
8041         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
8042 
8043       return nullptr;
8044     }
8045 
8046     case Stmt::ArraySubscriptExprClass: {
8047       // Array subscripts are potential references to data on the stack.  We
8048       // retrieve the DeclRefExpr* for the array variable if it indeed
8049       // has local storage.
8050       const auto *ASE = cast<ArraySubscriptExpr>(E);
8051       if (ASE->isTypeDependent())
8052         return nullptr;
8053       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8054     }
8055 
8056     case Stmt::OMPArraySectionExprClass: {
8057       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8058                       ParentDecl);
8059     }
8060 
8061     case Stmt::ConditionalOperatorClass: {
8062       // For conditional operators we need to see if either the LHS or RHS are
8063       // non-NULL Expr's.  If one is non-NULL, we return it.
8064       const ConditionalOperator *C = cast<ConditionalOperator>(E);
8065 
8066       // Handle the GNU extension for missing LHS.
8067       if (const Expr *LHSExpr = C->getLHS()) {
8068         // In C++, we can have a throw-expression, which has 'void' type.
8069         if (!LHSExpr->getType()->isVoidType())
8070           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8071             return LHS;
8072       }
8073 
8074       // In C++, we can have a throw-expression, which has 'void' type.
8075       if (C->getRHS()->getType()->isVoidType())
8076         return nullptr;
8077 
8078       return EvalVal(C->getRHS(), refVars, ParentDecl);
8079     }
8080 
8081     // Accesses to members are potential references to data on the stack.
8082     case Stmt::MemberExprClass: {
8083       const MemberExpr *M = cast<MemberExpr>(E);
8084 
8085       // Check for indirect access.  We only want direct field accesses.
8086       if (M->isArrow())
8087         return nullptr;
8088 
8089       // Check whether the member type is itself a reference, in which case
8090       // we're not going to refer to the member, but to what the member refers
8091       // to.
8092       if (M->getMemberDecl()->getType()->isReferenceType())
8093         return nullptr;
8094 
8095       return EvalVal(M->getBase(), refVars, ParentDecl);
8096     }
8097 
8098     case Stmt::MaterializeTemporaryExprClass:
8099       if (const Expr *Result =
8100               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8101                       refVars, ParentDecl))
8102         return Result;
8103       return E;
8104 
8105     default:
8106       // Check that we don't return or take the address of a reference to a
8107       // temporary. This is only useful in C++.
8108       if (!E->isTypeDependent() && E->isRValue())
8109         return E;
8110 
8111       // Everything else: we simply don't reason about them.
8112       return nullptr;
8113     }
8114   } while (true);
8115 }
8116 
8117 void
8118 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8119                          SourceLocation ReturnLoc,
8120                          bool isObjCMethod,
8121                          const AttrVec *Attrs,
8122                          const FunctionDecl *FD) {
8123   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8124 
8125   // Check if the return value is null but should not be.
8126   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8127        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8128       CheckNonNullExpr(*this, RetValExp))
8129     Diag(ReturnLoc, diag::warn_null_ret)
8130       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8131 
8132   // C++11 [basic.stc.dynamic.allocation]p4:
8133   //   If an allocation function declared with a non-throwing
8134   //   exception-specification fails to allocate storage, it shall return
8135   //   a null pointer. Any other allocation function that fails to allocate
8136   //   storage shall indicate failure only by throwing an exception [...]
8137   if (FD) {
8138     OverloadedOperatorKind Op = FD->getOverloadedOperator();
8139     if (Op == OO_New || Op == OO_Array_New) {
8140       const FunctionProtoType *Proto
8141         = FD->getType()->castAs<FunctionProtoType>();
8142       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8143           CheckNonNullExpr(*this, RetValExp))
8144         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8145           << FD << getLangOpts().CPlusPlus11;
8146     }
8147   }
8148 }
8149 
8150 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8151 
8152 /// Check for comparisons of floating point operands using != and ==.
8153 /// Issue a warning if these are no self-comparisons, as they are not likely
8154 /// to do what the programmer intended.
8155 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8156   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8157   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8158 
8159   // Special case: check for x == x (which is OK).
8160   // Do not emit warnings for such cases.
8161   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8162     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8163       if (DRL->getDecl() == DRR->getDecl())
8164         return;
8165 
8166   // Special case: check for comparisons against literals that can be exactly
8167   //  represented by APFloat.  In such cases, do not emit a warning.  This
8168   //  is a heuristic: often comparison against such literals are used to
8169   //  detect if a value in a variable has not changed.  This clearly can
8170   //  lead to false negatives.
8171   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8172     if (FLL->isExact())
8173       return;
8174   } else
8175     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8176       if (FLR->isExact())
8177         return;
8178 
8179   // Check for comparisons with builtin types.
8180   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8181     if (CL->getBuiltinCallee())
8182       return;
8183 
8184   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8185     if (CR->getBuiltinCallee())
8186       return;
8187 
8188   // Emit the diagnostic.
8189   Diag(Loc, diag::warn_floatingpoint_eq)
8190     << LHS->getSourceRange() << RHS->getSourceRange();
8191 }
8192 
8193 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8194 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8195 
8196 namespace {
8197 
8198 /// Structure recording the 'active' range of an integer-valued
8199 /// expression.
8200 struct IntRange {
8201   /// The number of bits active in the int.
8202   unsigned Width;
8203 
8204   /// True if the int is known not to have negative values.
8205   bool NonNegative;
8206 
8207   IntRange(unsigned Width, bool NonNegative)
8208       : Width(Width), NonNegative(NonNegative) {}
8209 
8210   /// Returns the range of the bool type.
8211   static IntRange forBoolType() {
8212     return IntRange(1, true);
8213   }
8214 
8215   /// Returns the range of an opaque value of the given integral type.
8216   static IntRange forValueOfType(ASTContext &C, QualType T) {
8217     return forValueOfCanonicalType(C,
8218                           T->getCanonicalTypeInternal().getTypePtr());
8219   }
8220 
8221   /// Returns the range of an opaque value of a canonical integral type.
8222   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8223     assert(T->isCanonicalUnqualified());
8224 
8225     if (const VectorType *VT = dyn_cast<VectorType>(T))
8226       T = VT->getElementType().getTypePtr();
8227     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8228       T = CT->getElementType().getTypePtr();
8229     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8230       T = AT->getValueType().getTypePtr();
8231 
8232     if (!C.getLangOpts().CPlusPlus) {
8233       // For enum types in C code, use the underlying datatype.
8234       if (const EnumType *ET = dyn_cast<EnumType>(T))
8235         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8236     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8237       // For enum types in C++, use the known bit width of the enumerators.
8238       EnumDecl *Enum = ET->getDecl();
8239       // In C++11, enums can have a fixed underlying type. Use this type to
8240       // compute the range.
8241       if (Enum->isFixed()) {
8242         return IntRange(C.getIntWidth(QualType(T, 0)),
8243                         !ET->isSignedIntegerOrEnumerationType());
8244       }
8245 
8246       unsigned NumPositive = Enum->getNumPositiveBits();
8247       unsigned NumNegative = Enum->getNumNegativeBits();
8248 
8249       if (NumNegative == 0)
8250         return IntRange(NumPositive, true/*NonNegative*/);
8251       else
8252         return IntRange(std::max(NumPositive + 1, NumNegative),
8253                         false/*NonNegative*/);
8254     }
8255 
8256     const BuiltinType *BT = cast<BuiltinType>(T);
8257     assert(BT->isInteger());
8258 
8259     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8260   }
8261 
8262   /// Returns the "target" range of a canonical integral type, i.e.
8263   /// the range of values expressible in the type.
8264   ///
8265   /// This matches forValueOfCanonicalType except that enums have the
8266   /// full range of their type, not the range of their enumerators.
8267   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8268     assert(T->isCanonicalUnqualified());
8269 
8270     if (const VectorType *VT = dyn_cast<VectorType>(T))
8271       T = VT->getElementType().getTypePtr();
8272     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8273       T = CT->getElementType().getTypePtr();
8274     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8275       T = AT->getValueType().getTypePtr();
8276     if (const EnumType *ET = dyn_cast<EnumType>(T))
8277       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8278 
8279     const BuiltinType *BT = cast<BuiltinType>(T);
8280     assert(BT->isInteger());
8281 
8282     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8283   }
8284 
8285   /// Returns the supremum of two ranges: i.e. their conservative merge.
8286   static IntRange join(IntRange L, IntRange R) {
8287     return IntRange(std::max(L.Width, R.Width),
8288                     L.NonNegative && R.NonNegative);
8289   }
8290 
8291   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8292   static IntRange meet(IntRange L, IntRange R) {
8293     return IntRange(std::min(L.Width, R.Width),
8294                     L.NonNegative || R.NonNegative);
8295   }
8296 };
8297 
8298 } // namespace
8299 
8300 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8301                               unsigned MaxWidth) {
8302   if (value.isSigned() && value.isNegative())
8303     return IntRange(value.getMinSignedBits(), false);
8304 
8305   if (value.getBitWidth() > MaxWidth)
8306     value = value.trunc(MaxWidth);
8307 
8308   // isNonNegative() just checks the sign bit without considering
8309   // signedness.
8310   return IntRange(value.getActiveBits(), true);
8311 }
8312 
8313 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8314                               unsigned MaxWidth) {
8315   if (result.isInt())
8316     return GetValueRange(C, result.getInt(), MaxWidth);
8317 
8318   if (result.isVector()) {
8319     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8320     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8321       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8322       R = IntRange::join(R, El);
8323     }
8324     return R;
8325   }
8326 
8327   if (result.isComplexInt()) {
8328     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8329     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8330     return IntRange::join(R, I);
8331   }
8332 
8333   // This can happen with lossless casts to intptr_t of "based" lvalues.
8334   // Assume it might use arbitrary bits.
8335   // FIXME: The only reason we need to pass the type in here is to get
8336   // the sign right on this one case.  It would be nice if APValue
8337   // preserved this.
8338   assert(result.isLValue() || result.isAddrLabelDiff());
8339   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8340 }
8341 
8342 static QualType GetExprType(const Expr *E) {
8343   QualType Ty = E->getType();
8344   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8345     Ty = AtomicRHS->getValueType();
8346   return Ty;
8347 }
8348 
8349 /// Pseudo-evaluate the given integer expression, estimating the
8350 /// range of values it might take.
8351 ///
8352 /// \param MaxWidth - the width to which the value will be truncated
8353 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8354   E = E->IgnoreParens();
8355 
8356   // Try a full evaluation first.
8357   Expr::EvalResult result;
8358   if (E->EvaluateAsRValue(result, C))
8359     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8360 
8361   // I think we only want to look through implicit casts here; if the
8362   // user has an explicit widening cast, we should treat the value as
8363   // being of the new, wider type.
8364   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8365     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8366       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8367 
8368     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8369 
8370     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8371                          CE->getCastKind() == CK_BooleanToSignedIntegral;
8372 
8373     // Assume that non-integer casts can span the full range of the type.
8374     if (!isIntegerCast)
8375       return OutputTypeRange;
8376 
8377     IntRange SubRange
8378       = GetExprRange(C, CE->getSubExpr(),
8379                      std::min(MaxWidth, OutputTypeRange.Width));
8380 
8381     // Bail out if the subexpr's range is as wide as the cast type.
8382     if (SubRange.Width >= OutputTypeRange.Width)
8383       return OutputTypeRange;
8384 
8385     // Otherwise, we take the smaller width, and we're non-negative if
8386     // either the output type or the subexpr is.
8387     return IntRange(SubRange.Width,
8388                     SubRange.NonNegative || OutputTypeRange.NonNegative);
8389   }
8390 
8391   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8392     // If we can fold the condition, just take that operand.
8393     bool CondResult;
8394     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8395       return GetExprRange(C, CondResult ? CO->getTrueExpr()
8396                                         : CO->getFalseExpr(),
8397                           MaxWidth);
8398 
8399     // Otherwise, conservatively merge.
8400     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8401     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8402     return IntRange::join(L, R);
8403   }
8404 
8405   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8406     switch (BO->getOpcode()) {
8407     case BO_Cmp:
8408       llvm_unreachable("builtin <=> should have class type");
8409 
8410     // Boolean-valued operations are single-bit and positive.
8411     case BO_LAnd:
8412     case BO_LOr:
8413     case BO_LT:
8414     case BO_GT:
8415     case BO_LE:
8416     case BO_GE:
8417     case BO_EQ:
8418     case BO_NE:
8419       return IntRange::forBoolType();
8420 
8421     // The type of the assignments is the type of the LHS, so the RHS
8422     // is not necessarily the same type.
8423     case BO_MulAssign:
8424     case BO_DivAssign:
8425     case BO_RemAssign:
8426     case BO_AddAssign:
8427     case BO_SubAssign:
8428     case BO_XorAssign:
8429     case BO_OrAssign:
8430       // TODO: bitfields?
8431       return IntRange::forValueOfType(C, GetExprType(E));
8432 
8433     // Simple assignments just pass through the RHS, which will have
8434     // been coerced to the LHS type.
8435     case BO_Assign:
8436       // TODO: bitfields?
8437       return GetExprRange(C, BO->getRHS(), MaxWidth);
8438 
8439     // Operations with opaque sources are black-listed.
8440     case BO_PtrMemD:
8441     case BO_PtrMemI:
8442       return IntRange::forValueOfType(C, GetExprType(E));
8443 
8444     // Bitwise-and uses the *infinum* of the two source ranges.
8445     case BO_And:
8446     case BO_AndAssign:
8447       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8448                             GetExprRange(C, BO->getRHS(), MaxWidth));
8449 
8450     // Left shift gets black-listed based on a judgement call.
8451     case BO_Shl:
8452       // ...except that we want to treat '1 << (blah)' as logically
8453       // positive.  It's an important idiom.
8454       if (IntegerLiteral *I
8455             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8456         if (I->getValue() == 1) {
8457           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8458           return IntRange(R.Width, /*NonNegative*/ true);
8459         }
8460       }
8461       LLVM_FALLTHROUGH;
8462 
8463     case BO_ShlAssign:
8464       return IntRange::forValueOfType(C, GetExprType(E));
8465 
8466     // Right shift by a constant can narrow its left argument.
8467     case BO_Shr:
8468     case BO_ShrAssign: {
8469       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8470 
8471       // If the shift amount is a positive constant, drop the width by
8472       // that much.
8473       llvm::APSInt shift;
8474       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8475           shift.isNonNegative()) {
8476         unsigned zext = shift.getZExtValue();
8477         if (zext >= L.Width)
8478           L.Width = (L.NonNegative ? 0 : 1);
8479         else
8480           L.Width -= zext;
8481       }
8482 
8483       return L;
8484     }
8485 
8486     // Comma acts as its right operand.
8487     case BO_Comma:
8488       return GetExprRange(C, BO->getRHS(), MaxWidth);
8489 
8490     // Black-list pointer subtractions.
8491     case BO_Sub:
8492       if (BO->getLHS()->getType()->isPointerType())
8493         return IntRange::forValueOfType(C, GetExprType(E));
8494       break;
8495 
8496     // The width of a division result is mostly determined by the size
8497     // of the LHS.
8498     case BO_Div: {
8499       // Don't 'pre-truncate' the operands.
8500       unsigned opWidth = C.getIntWidth(GetExprType(E));
8501       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8502 
8503       // If the divisor is constant, use that.
8504       llvm::APSInt divisor;
8505       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8506         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8507         if (log2 >= L.Width)
8508           L.Width = (L.NonNegative ? 0 : 1);
8509         else
8510           L.Width = std::min(L.Width - log2, MaxWidth);
8511         return L;
8512       }
8513 
8514       // Otherwise, just use the LHS's width.
8515       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8516       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8517     }
8518 
8519     // The result of a remainder can't be larger than the result of
8520     // either side.
8521     case BO_Rem: {
8522       // Don't 'pre-truncate' the operands.
8523       unsigned opWidth = C.getIntWidth(GetExprType(E));
8524       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8525       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8526 
8527       IntRange meet = IntRange::meet(L, R);
8528       meet.Width = std::min(meet.Width, MaxWidth);
8529       return meet;
8530     }
8531 
8532     // The default behavior is okay for these.
8533     case BO_Mul:
8534     case BO_Add:
8535     case BO_Xor:
8536     case BO_Or:
8537       break;
8538     }
8539 
8540     // The default case is to treat the operation as if it were closed
8541     // on the narrowest type that encompasses both operands.
8542     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8543     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8544     return IntRange::join(L, R);
8545   }
8546 
8547   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8548     switch (UO->getOpcode()) {
8549     // Boolean-valued operations are white-listed.
8550     case UO_LNot:
8551       return IntRange::forBoolType();
8552 
8553     // Operations with opaque sources are black-listed.
8554     case UO_Deref:
8555     case UO_AddrOf: // should be impossible
8556       return IntRange::forValueOfType(C, GetExprType(E));
8557 
8558     default:
8559       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8560     }
8561   }
8562 
8563   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8564     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8565 
8566   if (const auto *BitField = E->getSourceBitField())
8567     return IntRange(BitField->getBitWidthValue(C),
8568                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8569 
8570   return IntRange::forValueOfType(C, GetExprType(E));
8571 }
8572 
8573 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
8574   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8575 }
8576 
8577 /// Checks whether the given value, which currently has the given
8578 /// source semantics, has the same value when coerced through the
8579 /// target semantics.
8580 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8581                                  const llvm::fltSemantics &Src,
8582                                  const llvm::fltSemantics &Tgt) {
8583   llvm::APFloat truncated = value;
8584 
8585   bool ignored;
8586   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8587   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8588 
8589   return truncated.bitwiseIsEqual(value);
8590 }
8591 
8592 /// Checks whether the given value, which currently has the given
8593 /// source semantics, has the same value when coerced through the
8594 /// target semantics.
8595 ///
8596 /// The value might be a vector of floats (or a complex number).
8597 static bool IsSameFloatAfterCast(const APValue &value,
8598                                  const llvm::fltSemantics &Src,
8599                                  const llvm::fltSemantics &Tgt) {
8600   if (value.isFloat())
8601     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8602 
8603   if (value.isVector()) {
8604     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8605       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8606         return false;
8607     return true;
8608   }
8609 
8610   assert(value.isComplexFloat());
8611   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8612           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8613 }
8614 
8615 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8616 
8617 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
8618   // Suppress cases where we are comparing against an enum constant.
8619   if (const DeclRefExpr *DR =
8620       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8621     if (isa<EnumConstantDecl>(DR->getDecl()))
8622       return true;
8623 
8624   // Suppress cases where the '0' value is expanded from a macro.
8625   if (E->getLocStart().isMacroID())
8626     return true;
8627 
8628   return false;
8629 }
8630 
8631 static bool isKnownToHaveUnsignedValue(Expr *E) {
8632   return E->getType()->isIntegerType() &&
8633          (!E->getType()->isSignedIntegerType() ||
8634           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8635 }
8636 
8637 namespace {
8638 /// The promoted range of values of a type. In general this has the
8639 /// following structure:
8640 ///
8641 ///     |-----------| . . . |-----------|
8642 ///     ^           ^       ^           ^
8643 ///    Min       HoleMin  HoleMax      Max
8644 ///
8645 /// ... where there is only a hole if a signed type is promoted to unsigned
8646 /// (in which case Min and Max are the smallest and largest representable
8647 /// values).
8648 struct PromotedRange {
8649   // Min, or HoleMax if there is a hole.
8650   llvm::APSInt PromotedMin;
8651   // Max, or HoleMin if there is a hole.
8652   llvm::APSInt PromotedMax;
8653 
8654   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
8655     if (R.Width == 0)
8656       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8657     else if (R.Width >= BitWidth && !Unsigned) {
8658       // Promotion made the type *narrower*. This happens when promoting
8659       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
8660       // Treat all values of 'signed int' as being in range for now.
8661       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8662       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8663     } else {
8664       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8665                         .extOrTrunc(BitWidth);
8666       PromotedMin.setIsUnsigned(Unsigned);
8667 
8668       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8669                         .extOrTrunc(BitWidth);
8670       PromotedMax.setIsUnsigned(Unsigned);
8671     }
8672   }
8673 
8674   // Determine whether this range is contiguous (has no hole).
8675   bool isContiguous() const { return PromotedMin <= PromotedMax; }
8676 
8677   // Where a constant value is within the range.
8678   enum ComparisonResult {
8679     LT = 0x1,
8680     LE = 0x2,
8681     GT = 0x4,
8682     GE = 0x8,
8683     EQ = 0x10,
8684     NE = 0x20,
8685     InRangeFlag = 0x40,
8686 
8687     Less = LE | LT | NE,
8688     Min = LE | InRangeFlag,
8689     InRange = InRangeFlag,
8690     Max = GE | InRangeFlag,
8691     Greater = GE | GT | NE,
8692 
8693     OnlyValue = LE | GE | EQ | InRangeFlag,
8694     InHole = NE
8695   };
8696 
8697   ComparisonResult compare(const llvm::APSInt &Value) const {
8698     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8699            Value.isUnsigned() == PromotedMin.isUnsigned());
8700     if (!isContiguous()) {
8701       assert(Value.isUnsigned() && "discontiguous range for signed compare");
8702       if (Value.isMinValue()) return Min;
8703       if (Value.isMaxValue()) return Max;
8704       if (Value >= PromotedMin) return InRange;
8705       if (Value <= PromotedMax) return InRange;
8706       return InHole;
8707     }
8708 
8709     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8710     case -1: return Less;
8711     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
8712     case 1:
8713       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8714       case -1: return InRange;
8715       case 0: return Max;
8716       case 1: return Greater;
8717       }
8718     }
8719 
8720     llvm_unreachable("impossible compare result");
8721   }
8722 
8723   static llvm::Optional<StringRef>
8724   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
8725     if (Op == BO_Cmp) {
8726       ComparisonResult LTFlag = LT, GTFlag = GT;
8727       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
8728 
8729       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
8730       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
8731       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
8732       return llvm::None;
8733     }
8734 
8735     ComparisonResult TrueFlag, FalseFlag;
8736     if (Op == BO_EQ) {
8737       TrueFlag = EQ;
8738       FalseFlag = NE;
8739     } else if (Op == BO_NE) {
8740       TrueFlag = NE;
8741       FalseFlag = EQ;
8742     } else {
8743       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8744         TrueFlag = LT;
8745         FalseFlag = GE;
8746       } else {
8747         TrueFlag = GT;
8748         FalseFlag = LE;
8749       }
8750       if (Op == BO_GE || Op == BO_LE)
8751         std::swap(TrueFlag, FalseFlag);
8752     }
8753     if (R & TrueFlag)
8754       return StringRef("true");
8755     if (R & FalseFlag)
8756       return StringRef("false");
8757     return llvm::None;
8758   }
8759 };
8760 }
8761 
8762 static bool HasEnumType(Expr *E) {
8763   // Strip off implicit integral promotions.
8764   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8765     if (ICE->getCastKind() != CK_IntegralCast &&
8766         ICE->getCastKind() != CK_NoOp)
8767       break;
8768     E = ICE->getSubExpr();
8769   }
8770 
8771   return E->getType()->isEnumeralType();
8772 }
8773 
8774 static int classifyConstantValue(Expr *Constant) {
8775   // The values of this enumeration are used in the diagnostics
8776   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
8777   enum ConstantValueKind {
8778     Miscellaneous = 0,
8779     LiteralTrue,
8780     LiteralFalse
8781   };
8782   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8783     return BL->getValue() ? ConstantValueKind::LiteralTrue
8784                           : ConstantValueKind::LiteralFalse;
8785   return ConstantValueKind::Miscellaneous;
8786 }
8787 
8788 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8789                                         Expr *Constant, Expr *Other,
8790                                         const llvm::APSInt &Value,
8791                                         bool RhsConstant) {
8792   if (S.inTemplateInstantiation())
8793     return false;
8794 
8795   Expr *OriginalOther = Other;
8796 
8797   Constant = Constant->IgnoreParenImpCasts();
8798   Other = Other->IgnoreParenImpCasts();
8799 
8800   // Suppress warnings on tautological comparisons between values of the same
8801   // enumeration type. There are only two ways we could warn on this:
8802   //  - If the constant is outside the range of representable values of
8803   //    the enumeration. In such a case, we should warn about the cast
8804   //    to enumeration type, not about the comparison.
8805   //  - If the constant is the maximum / minimum in-range value. For an
8806   //    enumeratin type, such comparisons can be meaningful and useful.
8807   if (Constant->getType()->isEnumeralType() &&
8808       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
8809     return false;
8810 
8811   // TODO: Investigate using GetExprRange() to get tighter bounds
8812   // on the bit ranges.
8813   QualType OtherT = Other->getType();
8814   if (const auto *AT = OtherT->getAs<AtomicType>())
8815     OtherT = AT->getValueType();
8816   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8817 
8818   // Whether we're treating Other as being a bool because of the form of
8819   // expression despite it having another type (typically 'int' in C).
8820   bool OtherIsBooleanDespiteType =
8821       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
8822   if (OtherIsBooleanDespiteType)
8823     OtherRange = IntRange::forBoolType();
8824 
8825   // Determine the promoted range of the other type and see if a comparison of
8826   // the constant against that range is tautological.
8827   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
8828                                    Value.isUnsigned());
8829   auto Cmp = OtherPromotedRange.compare(Value);
8830   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
8831   if (!Result)
8832     return false;
8833 
8834   // Suppress the diagnostic for an in-range comparison if the constant comes
8835   // from a macro or enumerator. We don't want to diagnose
8836   //
8837   //   some_long_value <= INT_MAX
8838   //
8839   // when sizeof(int) == sizeof(long).
8840   bool InRange = Cmp & PromotedRange::InRangeFlag;
8841   if (InRange && IsEnumConstOrFromMacro(S, Constant))
8842     return false;
8843 
8844   // If this is a comparison to an enum constant, include that
8845   // constant in the diagnostic.
8846   const EnumConstantDecl *ED = nullptr;
8847   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8848     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8849 
8850   // Should be enough for uint128 (39 decimal digits)
8851   SmallString<64> PrettySourceValue;
8852   llvm::raw_svector_ostream OS(PrettySourceValue);
8853   if (ED)
8854     OS << '\'' << *ED << "' (" << Value << ")";
8855   else
8856     OS << Value;
8857 
8858   // FIXME: We use a somewhat different formatting for the in-range cases and
8859   // cases involving boolean values for historical reasons. We should pick a
8860   // consistent way of presenting these diagnostics.
8861   if (!InRange || Other->isKnownToHaveBooleanValue()) {
8862     S.DiagRuntimeBehavior(
8863       E->getOperatorLoc(), E,
8864       S.PDiag(!InRange ? diag::warn_out_of_range_compare
8865                        : diag::warn_tautological_bool_compare)
8866           << OS.str() << classifyConstantValue(Constant)
8867           << OtherT << OtherIsBooleanDespiteType << *Result
8868           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8869   } else {
8870     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
8871                         ? (HasEnumType(OriginalOther)
8872                                ? diag::warn_unsigned_enum_always_true_comparison
8873                                : diag::warn_unsigned_always_true_comparison)
8874                         : diag::warn_tautological_constant_compare;
8875 
8876     S.Diag(E->getOperatorLoc(), Diag)
8877         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
8878         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8879   }
8880 
8881   return true;
8882 }
8883 
8884 /// Analyze the operands of the given comparison.  Implements the
8885 /// fallback case from AnalyzeComparison.
8886 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8887   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8888   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8889 }
8890 
8891 /// \brief Implements -Wsign-compare.
8892 ///
8893 /// \param E the binary operator to check for warnings
8894 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8895   // The type the comparison is being performed in.
8896   QualType T = E->getLHS()->getType();
8897 
8898   // Only analyze comparison operators where both sides have been converted to
8899   // the same type.
8900   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8901     return AnalyzeImpConvsInComparison(S, E);
8902 
8903   // Don't analyze value-dependent comparisons directly.
8904   if (E->isValueDependent())
8905     return AnalyzeImpConvsInComparison(S, E);
8906 
8907   Expr *LHS = E->getLHS();
8908   Expr *RHS = E->getRHS();
8909 
8910   if (T->isIntegralType(S.Context)) {
8911     llvm::APSInt RHSValue;
8912     llvm::APSInt LHSValue;
8913 
8914     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8915     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
8916 
8917     // We don't care about expressions whose result is a constant.
8918     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8919       return AnalyzeImpConvsInComparison(S, E);
8920 
8921     // We only care about expressions where just one side is literal
8922     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8923       // Is the constant on the RHS or LHS?
8924       const bool RhsConstant = IsRHSIntegralLiteral;
8925       Expr *Const = RhsConstant ? RHS : LHS;
8926       Expr *Other = RhsConstant ? LHS : RHS;
8927       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8928 
8929       // Check whether an integer constant comparison results in a value
8930       // of 'true' or 'false'.
8931       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8932         return AnalyzeImpConvsInComparison(S, E);
8933     }
8934   }
8935 
8936   if (!T->hasUnsignedIntegerRepresentation()) {
8937     // We don't do anything special if this isn't an unsigned integral
8938     // comparison:  we're only interested in integral comparisons, and
8939     // signed comparisons only happen in cases we don't care to warn about.
8940     return AnalyzeImpConvsInComparison(S, E);
8941   }
8942 
8943   LHS = LHS->IgnoreParenImpCasts();
8944   RHS = RHS->IgnoreParenImpCasts();
8945 
8946   if (!S.getLangOpts().CPlusPlus) {
8947     // Avoid warning about comparison of integers with different signs when
8948     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
8949     // the type of `E`.
8950     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
8951       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
8952     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
8953       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
8954   }
8955 
8956   // Check to see if one of the (unmodified) operands is of different
8957   // signedness.
8958   Expr *signedOperand, *unsignedOperand;
8959   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8960     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8961            "unsigned comparison between two signed integer expressions?");
8962     signedOperand = LHS;
8963     unsignedOperand = RHS;
8964   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8965     signedOperand = RHS;
8966     unsignedOperand = LHS;
8967   } else {
8968     return AnalyzeImpConvsInComparison(S, E);
8969   }
8970 
8971   // Otherwise, calculate the effective range of the signed operand.
8972   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8973 
8974   // Go ahead and analyze implicit conversions in the operands.  Note
8975   // that we skip the implicit conversions on both sides.
8976   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8977   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8978 
8979   // If the signed range is non-negative, -Wsign-compare won't fire.
8980   if (signedRange.NonNegative)
8981     return;
8982 
8983   // For (in)equality comparisons, if the unsigned operand is a
8984   // constant which cannot collide with a overflowed signed operand,
8985   // then reinterpreting the signed operand as unsigned will not
8986   // change the result of the comparison.
8987   if (E->isEqualityOp()) {
8988     unsigned comparisonWidth = S.Context.getIntWidth(T);
8989     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8990 
8991     // We should never be unable to prove that the unsigned operand is
8992     // non-negative.
8993     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8994 
8995     if (unsignedRange.Width < comparisonWidth)
8996       return;
8997   }
8998 
8999   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9000     S.PDiag(diag::warn_mixed_sign_comparison)
9001       << LHS->getType() << RHS->getType()
9002       << LHS->getSourceRange() << RHS->getSourceRange());
9003 }
9004 
9005 /// Analyzes an attempt to assign the given value to a bitfield.
9006 ///
9007 /// Returns true if there was something fishy about the attempt.
9008 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9009                                       SourceLocation InitLoc) {
9010   assert(Bitfield->isBitField());
9011   if (Bitfield->isInvalidDecl())
9012     return false;
9013 
9014   // White-list bool bitfields.
9015   QualType BitfieldType = Bitfield->getType();
9016   if (BitfieldType->isBooleanType())
9017      return false;
9018 
9019   if (BitfieldType->isEnumeralType()) {
9020     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9021     // If the underlying enum type was not explicitly specified as an unsigned
9022     // type and the enum contain only positive values, MSVC++ will cause an
9023     // inconsistency by storing this as a signed type.
9024     if (S.getLangOpts().CPlusPlus11 &&
9025         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9026         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9027         BitfieldEnumDecl->getNumNegativeBits() == 0) {
9028       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9029         << BitfieldEnumDecl->getNameAsString();
9030     }
9031   }
9032 
9033   if (Bitfield->getType()->isBooleanType())
9034     return false;
9035 
9036   // Ignore value- or type-dependent expressions.
9037   if (Bitfield->getBitWidth()->isValueDependent() ||
9038       Bitfield->getBitWidth()->isTypeDependent() ||
9039       Init->isValueDependent() ||
9040       Init->isTypeDependent())
9041     return false;
9042 
9043   Expr *OriginalInit = Init->IgnoreParenImpCasts();
9044   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
9045 
9046   llvm::APSInt Value;
9047   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9048                                    Expr::SE_AllowSideEffects)) {
9049     // The RHS is not constant.  If the RHS has an enum type, make sure the
9050     // bitfield is wide enough to hold all the values of the enum without
9051     // truncation.
9052     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9053       EnumDecl *ED = EnumTy->getDecl();
9054       bool SignedBitfield = BitfieldType->isSignedIntegerType();
9055 
9056       // Enum types are implicitly signed on Windows, so check if there are any
9057       // negative enumerators to see if the enum was intended to be signed or
9058       // not.
9059       bool SignedEnum = ED->getNumNegativeBits() > 0;
9060 
9061       // Check for surprising sign changes when assigning enum values to a
9062       // bitfield of different signedness.  If the bitfield is signed and we
9063       // have exactly the right number of bits to store this unsigned enum,
9064       // suggest changing the enum to an unsigned type. This typically happens
9065       // on Windows where unfixed enums always use an underlying type of 'int'.
9066       unsigned DiagID = 0;
9067       if (SignedEnum && !SignedBitfield) {
9068         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9069       } else if (SignedBitfield && !SignedEnum &&
9070                  ED->getNumPositiveBits() == FieldWidth) {
9071         DiagID = diag::warn_signed_bitfield_enum_conversion;
9072       }
9073 
9074       if (DiagID) {
9075         S.Diag(InitLoc, DiagID) << Bitfield << ED;
9076         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9077         SourceRange TypeRange =
9078             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9079         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9080             << SignedEnum << TypeRange;
9081       }
9082 
9083       // Compute the required bitwidth. If the enum has negative values, we need
9084       // one more bit than the normal number of positive bits to represent the
9085       // sign bit.
9086       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9087                                                   ED->getNumNegativeBits())
9088                                        : ED->getNumPositiveBits();
9089 
9090       // Check the bitwidth.
9091       if (BitsNeeded > FieldWidth) {
9092         Expr *WidthExpr = Bitfield->getBitWidth();
9093         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9094             << Bitfield << ED;
9095         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9096             << BitsNeeded << ED << WidthExpr->getSourceRange();
9097       }
9098     }
9099 
9100     return false;
9101   }
9102 
9103   unsigned OriginalWidth = Value.getBitWidth();
9104 
9105   if (!Value.isSigned() || Value.isNegative())
9106     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9107       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9108         OriginalWidth = Value.getMinSignedBits();
9109 
9110   if (OriginalWidth <= FieldWidth)
9111     return false;
9112 
9113   // Compute the value which the bitfield will contain.
9114   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9115   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9116 
9117   // Check whether the stored value is equal to the original value.
9118   TruncatedValue = TruncatedValue.extend(OriginalWidth);
9119   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9120     return false;
9121 
9122   // Special-case bitfields of width 1: booleans are naturally 0/1, and
9123   // therefore don't strictly fit into a signed bitfield of width 1.
9124   if (FieldWidth == 1 && Value == 1)
9125     return false;
9126 
9127   std::string PrettyValue = Value.toString(10);
9128   std::string PrettyTrunc = TruncatedValue.toString(10);
9129 
9130   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9131     << PrettyValue << PrettyTrunc << OriginalInit->getType()
9132     << Init->getSourceRange();
9133 
9134   return true;
9135 }
9136 
9137 /// Analyze the given simple or compound assignment for warning-worthy
9138 /// operations.
9139 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9140   // Just recurse on the LHS.
9141   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9142 
9143   // We want to recurse on the RHS as normal unless we're assigning to
9144   // a bitfield.
9145   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9146     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9147                                   E->getOperatorLoc())) {
9148       // Recurse, ignoring any implicit conversions on the RHS.
9149       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9150                                         E->getOperatorLoc());
9151     }
9152   }
9153 
9154   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9155 }
9156 
9157 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9158 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9159                             SourceLocation CContext, unsigned diag,
9160                             bool pruneControlFlow = false) {
9161   if (pruneControlFlow) {
9162     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9163                           S.PDiag(diag)
9164                             << SourceType << T << E->getSourceRange()
9165                             << SourceRange(CContext));
9166     return;
9167   }
9168   S.Diag(E->getExprLoc(), diag)
9169     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9170 }
9171 
9172 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9173 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9174                             SourceLocation CContext,
9175                             unsigned diag, bool pruneControlFlow = false) {
9176   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9177 }
9178 
9179 /// Analyze the given compound assignment for the possible losing of
9180 /// floating-point precision.
9181 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
9182   assert(isa<CompoundAssignOperator>(E) &&
9183          "Must be compound assignment operation");
9184   // Recurse on the LHS and RHS in here
9185   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9186   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9187 
9188   // Now check the outermost expression
9189   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
9190   const auto *RBT = cast<CompoundAssignOperator>(E)
9191                         ->getComputationResultType()
9192                         ->getAs<BuiltinType>();
9193 
9194   // If both source and target are floating points.
9195   if (ResultBT && ResultBT->isFloatingPoint() && RBT && RBT->isFloatingPoint())
9196     // Builtin FP kinds are ordered by increasing FP rank.
9197     if (ResultBT->getKind() < RBT->getKind())
9198       // We don't want to warn for system macro.
9199       if (!S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
9200         // warn about dropping FP rank.
9201         DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(),
9202                         E->getOperatorLoc(),
9203                         diag::warn_impcast_float_result_precision);
9204 }
9205 
9206 /// Diagnose an implicit cast from a floating point value to an integer value.
9207 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9208                                     SourceLocation CContext) {
9209   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9210   const bool PruneWarnings = S.inTemplateInstantiation();
9211 
9212   Expr *InnerE = E->IgnoreParenImpCasts();
9213   // We also want to warn on, e.g., "int i = -1.234"
9214   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9215     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9216       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9217 
9218   const bool IsLiteral =
9219       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9220 
9221   llvm::APFloat Value(0.0);
9222   bool IsConstant =
9223     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9224   if (!IsConstant) {
9225     return DiagnoseImpCast(S, E, T, CContext,
9226                            diag::warn_impcast_float_integer, PruneWarnings);
9227   }
9228 
9229   bool isExact = false;
9230 
9231   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9232                             T->hasUnsignedIntegerRepresentation());
9233   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9234                              &isExact) == llvm::APFloat::opOK &&
9235       isExact) {
9236     if (IsLiteral) return;
9237     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9238                            PruneWarnings);
9239   }
9240 
9241   unsigned DiagID = 0;
9242   if (IsLiteral) {
9243     // Warn on floating point literal to integer.
9244     DiagID = diag::warn_impcast_literal_float_to_integer;
9245   } else if (IntegerValue == 0) {
9246     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
9247       return DiagnoseImpCast(S, E, T, CContext,
9248                              diag::warn_impcast_float_integer, PruneWarnings);
9249     }
9250     // Warn on non-zero to zero conversion.
9251     DiagID = diag::warn_impcast_float_to_integer_zero;
9252   } else {
9253     if (IntegerValue.isUnsigned()) {
9254       if (!IntegerValue.isMaxValue()) {
9255         return DiagnoseImpCast(S, E, T, CContext,
9256                                diag::warn_impcast_float_integer, PruneWarnings);
9257       }
9258     } else {  // IntegerValue.isSigned()
9259       if (!IntegerValue.isMaxSignedValue() &&
9260           !IntegerValue.isMinSignedValue()) {
9261         return DiagnoseImpCast(S, E, T, CContext,
9262                                diag::warn_impcast_float_integer, PruneWarnings);
9263       }
9264     }
9265     // Warn on evaluatable floating point expression to integer conversion.
9266     DiagID = diag::warn_impcast_float_to_integer;
9267   }
9268 
9269   // FIXME: Force the precision of the source value down so we don't print
9270   // digits which are usually useless (we don't really care here if we
9271   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9272   // would automatically print the shortest representation, but it's a bit
9273   // tricky to implement.
9274   SmallString<16> PrettySourceValue;
9275   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9276   precision = (precision * 59 + 195) / 196;
9277   Value.toString(PrettySourceValue, precision);
9278 
9279   SmallString<16> PrettyTargetValue;
9280   if (IsBool)
9281     PrettyTargetValue = Value.isZero() ? "false" : "true";
9282   else
9283     IntegerValue.toString(PrettyTargetValue);
9284 
9285   if (PruneWarnings) {
9286     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9287                           S.PDiag(DiagID)
9288                               << E->getType() << T.getUnqualifiedType()
9289                               << PrettySourceValue << PrettyTargetValue
9290                               << E->getSourceRange() << SourceRange(CContext));
9291   } else {
9292     S.Diag(E->getExprLoc(), DiagID)
9293         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9294         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9295   }
9296 }
9297 
9298 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9299                                       IntRange Range) {
9300   if (!Range.Width) return "0";
9301 
9302   llvm::APSInt ValueInRange = Value;
9303   ValueInRange.setIsSigned(!Range.NonNegative);
9304   ValueInRange = ValueInRange.trunc(Range.Width);
9305   return ValueInRange.toString(10);
9306 }
9307 
9308 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9309   if (!isa<ImplicitCastExpr>(Ex))
9310     return false;
9311 
9312   Expr *InnerE = Ex->IgnoreParenImpCasts();
9313   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9314   const Type *Source =
9315     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9316   if (Target->isDependentType())
9317     return false;
9318 
9319   const BuiltinType *FloatCandidateBT =
9320     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9321   const Type *BoolCandidateType = ToBool ? Target : Source;
9322 
9323   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9324           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9325 }
9326 
9327 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9328                                              SourceLocation CC) {
9329   unsigned NumArgs = TheCall->getNumArgs();
9330   for (unsigned i = 0; i < NumArgs; ++i) {
9331     Expr *CurrA = TheCall->getArg(i);
9332     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9333       continue;
9334 
9335     bool IsSwapped = ((i > 0) &&
9336         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9337     IsSwapped |= ((i < (NumArgs - 1)) &&
9338         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9339     if (IsSwapped) {
9340       // Warn on this floating-point to bool conversion.
9341       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9342                       CurrA->getType(), CC,
9343                       diag::warn_impcast_floating_point_to_bool);
9344     }
9345   }
9346 }
9347 
9348 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9349                                    SourceLocation CC) {
9350   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9351                         E->getExprLoc()))
9352     return;
9353 
9354   // Don't warn on functions which have return type nullptr_t.
9355   if (isa<CallExpr>(E))
9356     return;
9357 
9358   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9359   const Expr::NullPointerConstantKind NullKind =
9360       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9361   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9362     return;
9363 
9364   // Return if target type is a safe conversion.
9365   if (T->isAnyPointerType() || T->isBlockPointerType() ||
9366       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9367     return;
9368 
9369   SourceLocation Loc = E->getSourceRange().getBegin();
9370 
9371   // Venture through the macro stacks to get to the source of macro arguments.
9372   // The new location is a better location than the complete location that was
9373   // passed in.
9374   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9375   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
9376 
9377   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
9378   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9379     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9380         Loc, S.SourceMgr, S.getLangOpts());
9381     if (MacroName == "NULL")
9382       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9383   }
9384 
9385   // Only warn if the null and context location are in the same macro expansion.
9386   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9387     return;
9388 
9389   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9390       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
9391       << FixItHint::CreateReplacement(Loc,
9392                                       S.getFixItZeroLiteralForType(T, Loc));
9393 }
9394 
9395 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9396                                   ObjCArrayLiteral *ArrayLiteral);
9397 
9398 static void
9399 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9400                            ObjCDictionaryLiteral *DictionaryLiteral);
9401 
9402 /// Check a single element within a collection literal against the
9403 /// target element type.
9404 static void checkObjCCollectionLiteralElement(Sema &S,
9405                                               QualType TargetElementType,
9406                                               Expr *Element,
9407                                               unsigned ElementKind) {
9408   // Skip a bitcast to 'id' or qualified 'id'.
9409   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9410     if (ICE->getCastKind() == CK_BitCast &&
9411         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9412       Element = ICE->getSubExpr();
9413   }
9414 
9415   QualType ElementType = Element->getType();
9416   ExprResult ElementResult(Element);
9417   if (ElementType->getAs<ObjCObjectPointerType>() &&
9418       S.CheckSingleAssignmentConstraints(TargetElementType,
9419                                          ElementResult,
9420                                          false, false)
9421         != Sema::Compatible) {
9422     S.Diag(Element->getLocStart(),
9423            diag::warn_objc_collection_literal_element)
9424       << ElementType << ElementKind << TargetElementType
9425       << Element->getSourceRange();
9426   }
9427 
9428   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9429     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9430   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9431     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9432 }
9433 
9434 /// Check an Objective-C array literal being converted to the given
9435 /// target type.
9436 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9437                                   ObjCArrayLiteral *ArrayLiteral) {
9438   if (!S.NSArrayDecl)
9439     return;
9440 
9441   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9442   if (!TargetObjCPtr)
9443     return;
9444 
9445   if (TargetObjCPtr->isUnspecialized() ||
9446       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9447         != S.NSArrayDecl->getCanonicalDecl())
9448     return;
9449 
9450   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9451   if (TypeArgs.size() != 1)
9452     return;
9453 
9454   QualType TargetElementType = TypeArgs[0];
9455   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9456     checkObjCCollectionLiteralElement(S, TargetElementType,
9457                                       ArrayLiteral->getElement(I),
9458                                       0);
9459   }
9460 }
9461 
9462 /// Check an Objective-C dictionary literal being converted to the given
9463 /// target type.
9464 static void
9465 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9466                            ObjCDictionaryLiteral *DictionaryLiteral) {
9467   if (!S.NSDictionaryDecl)
9468     return;
9469 
9470   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9471   if (!TargetObjCPtr)
9472     return;
9473 
9474   if (TargetObjCPtr->isUnspecialized() ||
9475       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9476         != S.NSDictionaryDecl->getCanonicalDecl())
9477     return;
9478 
9479   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9480   if (TypeArgs.size() != 2)
9481     return;
9482 
9483   QualType TargetKeyType = TypeArgs[0];
9484   QualType TargetObjectType = TypeArgs[1];
9485   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9486     auto Element = DictionaryLiteral->getKeyValueElement(I);
9487     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9488     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9489   }
9490 }
9491 
9492 // Helper function to filter out cases for constant width constant conversion.
9493 // Don't warn on char array initialization or for non-decimal values.
9494 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9495                                           SourceLocation CC) {
9496   // If initializing from a constant, and the constant starts with '0',
9497   // then it is a binary, octal, or hexadecimal.  Allow these constants
9498   // to fill all the bits, even if there is a sign change.
9499   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9500     const char FirstLiteralCharacter =
9501         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9502     if (FirstLiteralCharacter == '0')
9503       return false;
9504   }
9505 
9506   // If the CC location points to a '{', and the type is char, then assume
9507   // assume it is an array initialization.
9508   if (CC.isValid() && T->isCharType()) {
9509     const char FirstContextCharacter =
9510         S.getSourceManager().getCharacterData(CC)[0];
9511     if (FirstContextCharacter == '{')
9512       return false;
9513   }
9514 
9515   return true;
9516 }
9517 
9518 static void
9519 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9520                         bool *ICContext = nullptr) {
9521   if (E->isTypeDependent() || E->isValueDependent()) return;
9522 
9523   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9524   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9525   if (Source == Target) return;
9526   if (Target->isDependentType()) return;
9527 
9528   // If the conversion context location is invalid don't complain. We also
9529   // don't want to emit a warning if the issue occurs from the expansion of
9530   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9531   // delay this check as long as possible. Once we detect we are in that
9532   // scenario, we just return.
9533   if (CC.isInvalid())
9534     return;
9535 
9536   // Diagnose implicit casts to bool.
9537   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9538     if (isa<StringLiteral>(E))
9539       // Warn on string literal to bool.  Checks for string literals in logical
9540       // and expressions, for instance, assert(0 && "error here"), are
9541       // prevented by a check in AnalyzeImplicitConversions().
9542       return DiagnoseImpCast(S, E, T, CC,
9543                              diag::warn_impcast_string_literal_to_bool);
9544     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9545         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9546       // This covers the literal expressions that evaluate to Objective-C
9547       // objects.
9548       return DiagnoseImpCast(S, E, T, CC,
9549                              diag::warn_impcast_objective_c_literal_to_bool);
9550     }
9551     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9552       // Warn on pointer to bool conversion that is always true.
9553       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9554                                      SourceRange(CC));
9555     }
9556   }
9557 
9558   // Check implicit casts from Objective-C collection literals to specialized
9559   // collection types, e.g., NSArray<NSString *> *.
9560   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9561     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9562   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9563     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9564 
9565   // Strip vector types.
9566   if (isa<VectorType>(Source)) {
9567     if (!isa<VectorType>(Target)) {
9568       if (S.SourceMgr.isInSystemMacro(CC))
9569         return;
9570       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9571     }
9572 
9573     // If the vector cast is cast between two vectors of the same size, it is
9574     // a bitcast, not a conversion.
9575     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9576       return;
9577 
9578     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9579     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9580   }
9581   if (auto VecTy = dyn_cast<VectorType>(Target))
9582     Target = VecTy->getElementType().getTypePtr();
9583 
9584   // Strip complex types.
9585   if (isa<ComplexType>(Source)) {
9586     if (!isa<ComplexType>(Target)) {
9587       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
9588         return;
9589 
9590       return DiagnoseImpCast(S, E, T, CC,
9591                              S.getLangOpts().CPlusPlus
9592                                  ? diag::err_impcast_complex_scalar
9593                                  : diag::warn_impcast_complex_scalar);
9594     }
9595 
9596     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9597     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9598   }
9599 
9600   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9601   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9602 
9603   // If the source is floating point...
9604   if (SourceBT && SourceBT->isFloatingPoint()) {
9605     // ...and the target is floating point...
9606     if (TargetBT && TargetBT->isFloatingPoint()) {
9607       // ...then warn if we're dropping FP rank.
9608 
9609       // Builtin FP kinds are ordered by increasing FP rank.
9610       if (SourceBT->getKind() > TargetBT->getKind()) {
9611         // Don't warn about float constants that are precisely
9612         // representable in the target type.
9613         Expr::EvalResult result;
9614         if (E->EvaluateAsRValue(result, S.Context)) {
9615           // Value might be a float, a float vector, or a float complex.
9616           if (IsSameFloatAfterCast(result.Val,
9617                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9618                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9619             return;
9620         }
9621 
9622         if (S.SourceMgr.isInSystemMacro(CC))
9623           return;
9624 
9625         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9626       }
9627       // ... or possibly if we're increasing rank, too
9628       else if (TargetBT->getKind() > SourceBT->getKind()) {
9629         if (S.SourceMgr.isInSystemMacro(CC))
9630           return;
9631 
9632         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9633       }
9634       return;
9635     }
9636 
9637     // If the target is integral, always warn.
9638     if (TargetBT && TargetBT->isInteger()) {
9639       if (S.SourceMgr.isInSystemMacro(CC))
9640         return;
9641 
9642       DiagnoseFloatingImpCast(S, E, T, CC);
9643     }
9644 
9645     // Detect the case where a call result is converted from floating-point to
9646     // to bool, and the final argument to the call is converted from bool, to
9647     // discover this typo:
9648     //
9649     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9650     //
9651     // FIXME: This is an incredibly special case; is there some more general
9652     // way to detect this class of misplaced-parentheses bug?
9653     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9654       // Check last argument of function call to see if it is an
9655       // implicit cast from a type matching the type the result
9656       // is being cast to.
9657       CallExpr *CEx = cast<CallExpr>(E);
9658       if (unsigned NumArgs = CEx->getNumArgs()) {
9659         Expr *LastA = CEx->getArg(NumArgs - 1);
9660         Expr *InnerE = LastA->IgnoreParenImpCasts();
9661         if (isa<ImplicitCastExpr>(LastA) &&
9662             InnerE->getType()->isBooleanType()) {
9663           // Warn on this floating-point to bool conversion
9664           DiagnoseImpCast(S, E, T, CC,
9665                           diag::warn_impcast_floating_point_to_bool);
9666         }
9667       }
9668     }
9669     return;
9670   }
9671 
9672   DiagnoseNullConversion(S, E, T, CC);
9673 
9674   S.DiscardMisalignedMemberAddress(Target, E);
9675 
9676   if (!Source->isIntegerType() || !Target->isIntegerType())
9677     return;
9678 
9679   // TODO: remove this early return once the false positives for constant->bool
9680   // in templates, macros, etc, are reduced or removed.
9681   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9682     return;
9683 
9684   IntRange SourceRange = GetExprRange(S.Context, E);
9685   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9686 
9687   if (SourceRange.Width > TargetRange.Width) {
9688     // If the source is a constant, use a default-on diagnostic.
9689     // TODO: this should happen for bitfield stores, too.
9690     llvm::APSInt Value(32);
9691     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9692       if (S.SourceMgr.isInSystemMacro(CC))
9693         return;
9694 
9695       std::string PrettySourceValue = Value.toString(10);
9696       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9697 
9698       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9699         S.PDiag(diag::warn_impcast_integer_precision_constant)
9700             << PrettySourceValue << PrettyTargetValue
9701             << E->getType() << T << E->getSourceRange()
9702             << clang::SourceRange(CC));
9703       return;
9704     }
9705 
9706     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9707     if (S.SourceMgr.isInSystemMacro(CC))
9708       return;
9709 
9710     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9711       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9712                              /* pruneControlFlow */ true);
9713     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9714   }
9715 
9716   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9717       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9718     // Warn when doing a signed to signed conversion, warn if the positive
9719     // source value is exactly the width of the target type, which will
9720     // cause a negative value to be stored.
9721 
9722     llvm::APSInt Value;
9723     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9724         !S.SourceMgr.isInSystemMacro(CC)) {
9725       if (isSameWidthConstantConversion(S, E, T, CC)) {
9726         std::string PrettySourceValue = Value.toString(10);
9727         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9728 
9729         S.DiagRuntimeBehavior(
9730             E->getExprLoc(), E,
9731             S.PDiag(diag::warn_impcast_integer_precision_constant)
9732                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9733                 << E->getSourceRange() << clang::SourceRange(CC));
9734         return;
9735       }
9736     }
9737 
9738     // Fall through for non-constants to give a sign conversion warning.
9739   }
9740 
9741   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9742       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9743        SourceRange.Width == TargetRange.Width)) {
9744     if (S.SourceMgr.isInSystemMacro(CC))
9745       return;
9746 
9747     unsigned DiagID = diag::warn_impcast_integer_sign;
9748 
9749     // Traditionally, gcc has warned about this under -Wsign-compare.
9750     // We also want to warn about it in -Wconversion.
9751     // So if -Wconversion is off, use a completely identical diagnostic
9752     // in the sign-compare group.
9753     // The conditional-checking code will
9754     if (ICContext) {
9755       DiagID = diag::warn_impcast_integer_sign_conditional;
9756       *ICContext = true;
9757     }
9758 
9759     return DiagnoseImpCast(S, E, T, CC, DiagID);
9760   }
9761 
9762   // Diagnose conversions between different enumeration types.
9763   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9764   // type, to give us better diagnostics.
9765   QualType SourceType = E->getType();
9766   if (!S.getLangOpts().CPlusPlus) {
9767     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9768       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9769         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9770         SourceType = S.Context.getTypeDeclType(Enum);
9771         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9772       }
9773   }
9774 
9775   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9776     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9777       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9778           TargetEnum->getDecl()->hasNameForLinkage() &&
9779           SourceEnum != TargetEnum) {
9780         if (S.SourceMgr.isInSystemMacro(CC))
9781           return;
9782 
9783         return DiagnoseImpCast(S, E, SourceType, T, CC,
9784                                diag::warn_impcast_different_enum_types);
9785       }
9786 }
9787 
9788 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9789                                      SourceLocation CC, QualType T);
9790 
9791 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9792                                     SourceLocation CC, bool &ICContext) {
9793   E = E->IgnoreParenImpCasts();
9794 
9795   if (isa<ConditionalOperator>(E))
9796     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9797 
9798   AnalyzeImplicitConversions(S, E, CC);
9799   if (E->getType() != T)
9800     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9801 }
9802 
9803 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9804                                      SourceLocation CC, QualType T) {
9805   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9806 
9807   bool Suspicious = false;
9808   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9809   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9810 
9811   // If -Wconversion would have warned about either of the candidates
9812   // for a signedness conversion to the context type...
9813   if (!Suspicious) return;
9814 
9815   // ...but it's currently ignored...
9816   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9817     return;
9818 
9819   // ...then check whether it would have warned about either of the
9820   // candidates for a signedness conversion to the condition type.
9821   if (E->getType() == T) return;
9822 
9823   Suspicious = false;
9824   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9825                           E->getType(), CC, &Suspicious);
9826   if (!Suspicious)
9827     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9828                             E->getType(), CC, &Suspicious);
9829 }
9830 
9831 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9832 /// Input argument E is a logical expression.
9833 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9834   if (S.getLangOpts().Bool)
9835     return;
9836   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9837 }
9838 
9839 /// AnalyzeImplicitConversions - Find and report any interesting
9840 /// implicit conversions in the given expression.  There are a couple
9841 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9842 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
9843                                        SourceLocation CC) {
9844   QualType T = OrigE->getType();
9845   Expr *E = OrigE->IgnoreParenImpCasts();
9846 
9847   if (E->isTypeDependent() || E->isValueDependent())
9848     return;
9849 
9850   // For conditional operators, we analyze the arguments as if they
9851   // were being fed directly into the output.
9852   if (isa<ConditionalOperator>(E)) {
9853     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9854     CheckConditionalOperator(S, CO, CC, T);
9855     return;
9856   }
9857 
9858   // Check implicit argument conversions for function calls.
9859   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9860     CheckImplicitArgumentConversions(S, Call, CC);
9861 
9862   // Go ahead and check any implicit conversions we might have skipped.
9863   // The non-canonical typecheck is just an optimization;
9864   // CheckImplicitConversion will filter out dead implicit conversions.
9865   if (E->getType() != T)
9866     CheckImplicitConversion(S, E, T, CC);
9867 
9868   // Now continue drilling into this expression.
9869 
9870   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9871     // The bound subexpressions in a PseudoObjectExpr are not reachable
9872     // as transitive children.
9873     // FIXME: Use a more uniform representation for this.
9874     for (auto *SE : POE->semantics())
9875       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9876         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9877   }
9878 
9879   // Skip past explicit casts.
9880   if (isa<ExplicitCastExpr>(E)) {
9881     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9882     return AnalyzeImplicitConversions(S, E, CC);
9883   }
9884 
9885   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9886     // Do a somewhat different check with comparison operators.
9887     if (BO->isComparisonOp())
9888       return AnalyzeComparison(S, BO);
9889 
9890     // And with simple assignments.
9891     if (BO->getOpcode() == BO_Assign)
9892       return AnalyzeAssignment(S, BO);
9893     // And with compound assignments.
9894     if (BO->isAssignmentOp())
9895       return AnalyzeCompoundAssignment(S, BO);
9896   }
9897 
9898   // These break the otherwise-useful invariant below.  Fortunately,
9899   // we don't really need to recurse into them, because any internal
9900   // expressions should have been analyzed already when they were
9901   // built into statements.
9902   if (isa<StmtExpr>(E)) return;
9903 
9904   // Don't descend into unevaluated contexts.
9905   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9906 
9907   // Now just recurse over the expression's children.
9908   CC = E->getExprLoc();
9909   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9910   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9911   for (Stmt *SubStmt : E->children()) {
9912     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9913     if (!ChildExpr)
9914       continue;
9915 
9916     if (IsLogicalAndOperator &&
9917         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9918       // Ignore checking string literals that are in logical and operators.
9919       // This is a common pattern for asserts.
9920       continue;
9921     AnalyzeImplicitConversions(S, ChildExpr, CC);
9922   }
9923 
9924   if (BO && BO->isLogicalOp()) {
9925     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9926     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9927       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9928 
9929     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9930     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9931       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9932   }
9933 
9934   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9935     if (U->getOpcode() == UO_LNot)
9936       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9937 }
9938 
9939 /// Diagnose integer type and any valid implicit convertion to it.
9940 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9941   // Taking into account implicit conversions,
9942   // allow any integer.
9943   if (!E->getType()->isIntegerType()) {
9944     S.Diag(E->getLocStart(),
9945            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9946     return true;
9947   }
9948   // Potentially emit standard warnings for implicit conversions if enabled
9949   // using -Wconversion.
9950   CheckImplicitConversion(S, E, IntT, E->getLocStart());
9951   return false;
9952 }
9953 
9954 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9955 // Returns true when emitting a warning about taking the address of a reference.
9956 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9957                               const PartialDiagnostic &PD) {
9958   E = E->IgnoreParenImpCasts();
9959 
9960   const FunctionDecl *FD = nullptr;
9961 
9962   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9963     if (!DRE->getDecl()->getType()->isReferenceType())
9964       return false;
9965   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9966     if (!M->getMemberDecl()->getType()->isReferenceType())
9967       return false;
9968   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9969     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9970       return false;
9971     FD = Call->getDirectCallee();
9972   } else {
9973     return false;
9974   }
9975 
9976   SemaRef.Diag(E->getExprLoc(), PD);
9977 
9978   // If possible, point to location of function.
9979   if (FD) {
9980     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9981   }
9982 
9983   return true;
9984 }
9985 
9986 // Returns true if the SourceLocation is expanded from any macro body.
9987 // Returns false if the SourceLocation is invalid, is from not in a macro
9988 // expansion, or is from expanded from a top-level macro argument.
9989 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9990   if (Loc.isInvalid())
9991     return false;
9992 
9993   while (Loc.isMacroID()) {
9994     if (SM.isMacroBodyExpansion(Loc))
9995       return true;
9996     Loc = SM.getImmediateMacroCallerLoc(Loc);
9997   }
9998 
9999   return false;
10000 }
10001 
10002 /// \brief Diagnose pointers that are always non-null.
10003 /// \param E the expression containing the pointer
10004 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10005 /// compared to a null pointer
10006 /// \param IsEqual True when the comparison is equal to a null pointer
10007 /// \param Range Extra SourceRange to highlight in the diagnostic
10008 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10009                                         Expr::NullPointerConstantKind NullKind,
10010                                         bool IsEqual, SourceRange Range) {
10011   if (!E)
10012     return;
10013 
10014   // Don't warn inside macros.
10015   if (E->getExprLoc().isMacroID()) {
10016     const SourceManager &SM = getSourceManager();
10017     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10018         IsInAnyMacroBody(SM, Range.getBegin()))
10019       return;
10020   }
10021   E = E->IgnoreImpCasts();
10022 
10023   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10024 
10025   if (isa<CXXThisExpr>(E)) {
10026     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10027                                 : diag::warn_this_bool_conversion;
10028     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10029     return;
10030   }
10031 
10032   bool IsAddressOf = false;
10033 
10034   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10035     if (UO->getOpcode() != UO_AddrOf)
10036       return;
10037     IsAddressOf = true;
10038     E = UO->getSubExpr();
10039   }
10040 
10041   if (IsAddressOf) {
10042     unsigned DiagID = IsCompare
10043                           ? diag::warn_address_of_reference_null_compare
10044                           : diag::warn_address_of_reference_bool_conversion;
10045     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10046                                          << IsEqual;
10047     if (CheckForReference(*this, E, PD)) {
10048       return;
10049     }
10050   }
10051 
10052   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10053     bool IsParam = isa<NonNullAttr>(NonnullAttr);
10054     std::string Str;
10055     llvm::raw_string_ostream S(Str);
10056     E->printPretty(S, nullptr, getPrintingPolicy());
10057     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10058                                 : diag::warn_cast_nonnull_to_bool;
10059     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10060       << E->getSourceRange() << Range << IsEqual;
10061     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10062   };
10063 
10064   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10065   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10066     if (auto *Callee = Call->getDirectCallee()) {
10067       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10068         ComplainAboutNonnullParamOrCall(A);
10069         return;
10070       }
10071     }
10072   }
10073 
10074   // Expect to find a single Decl.  Skip anything more complicated.
10075   ValueDecl *D = nullptr;
10076   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10077     D = R->getDecl();
10078   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10079     D = M->getMemberDecl();
10080   }
10081 
10082   // Weak Decls can be null.
10083   if (!D || D->isWeak())
10084     return;
10085 
10086   // Check for parameter decl with nonnull attribute
10087   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10088     if (getCurFunction() &&
10089         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10090       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10091         ComplainAboutNonnullParamOrCall(A);
10092         return;
10093       }
10094 
10095       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10096         auto ParamIter = llvm::find(FD->parameters(), PV);
10097         assert(ParamIter != FD->param_end());
10098         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10099 
10100         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10101           if (!NonNull->args_size()) {
10102               ComplainAboutNonnullParamOrCall(NonNull);
10103               return;
10104           }
10105 
10106           for (const ParamIdx &ArgNo : NonNull->args()) {
10107             if (ArgNo.getASTIndex() == ParamNo) {
10108               ComplainAboutNonnullParamOrCall(NonNull);
10109               return;
10110             }
10111           }
10112         }
10113       }
10114     }
10115   }
10116 
10117   QualType T = D->getType();
10118   const bool IsArray = T->isArrayType();
10119   const bool IsFunction = T->isFunctionType();
10120 
10121   // Address of function is used to silence the function warning.
10122   if (IsAddressOf && IsFunction) {
10123     return;
10124   }
10125 
10126   // Found nothing.
10127   if (!IsAddressOf && !IsFunction && !IsArray)
10128     return;
10129 
10130   // Pretty print the expression for the diagnostic.
10131   std::string Str;
10132   llvm::raw_string_ostream S(Str);
10133   E->printPretty(S, nullptr, getPrintingPolicy());
10134 
10135   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10136                               : diag::warn_impcast_pointer_to_bool;
10137   enum {
10138     AddressOf,
10139     FunctionPointer,
10140     ArrayPointer
10141   } DiagType;
10142   if (IsAddressOf)
10143     DiagType = AddressOf;
10144   else if (IsFunction)
10145     DiagType = FunctionPointer;
10146   else if (IsArray)
10147     DiagType = ArrayPointer;
10148   else
10149     llvm_unreachable("Could not determine diagnostic.");
10150   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10151                                 << Range << IsEqual;
10152 
10153   if (!IsFunction)
10154     return;
10155 
10156   // Suggest '&' to silence the function warning.
10157   Diag(E->getExprLoc(), diag::note_function_warning_silence)
10158       << FixItHint::CreateInsertion(E->getLocStart(), "&");
10159 
10160   // Check to see if '()' fixit should be emitted.
10161   QualType ReturnType;
10162   UnresolvedSet<4> NonTemplateOverloads;
10163   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10164   if (ReturnType.isNull())
10165     return;
10166 
10167   if (IsCompare) {
10168     // There are two cases here.  If there is null constant, the only suggest
10169     // for a pointer return type.  If the null is 0, then suggest if the return
10170     // type is a pointer or an integer type.
10171     if (!ReturnType->isPointerType()) {
10172       if (NullKind == Expr::NPCK_ZeroExpression ||
10173           NullKind == Expr::NPCK_ZeroLiteral) {
10174         if (!ReturnType->isIntegerType())
10175           return;
10176       } else {
10177         return;
10178       }
10179     }
10180   } else { // !IsCompare
10181     // For function to bool, only suggest if the function pointer has bool
10182     // return type.
10183     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10184       return;
10185   }
10186   Diag(E->getExprLoc(), diag::note_function_to_function_call)
10187       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10188 }
10189 
10190 /// Diagnoses "dangerous" implicit conversions within the given
10191 /// expression (which is a full expression).  Implements -Wconversion
10192 /// and -Wsign-compare.
10193 ///
10194 /// \param CC the "context" location of the implicit conversion, i.e.
10195 ///   the most location of the syntactic entity requiring the implicit
10196 ///   conversion
10197 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10198   // Don't diagnose in unevaluated contexts.
10199   if (isUnevaluatedContext())
10200     return;
10201 
10202   // Don't diagnose for value- or type-dependent expressions.
10203   if (E->isTypeDependent() || E->isValueDependent())
10204     return;
10205 
10206   // Check for array bounds violations in cases where the check isn't triggered
10207   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10208   // ArraySubscriptExpr is on the RHS of a variable initialization.
10209   CheckArrayAccess(E);
10210 
10211   // This is not the right CC for (e.g.) a variable initialization.
10212   AnalyzeImplicitConversions(*this, E, CC);
10213 }
10214 
10215 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10216 /// Input argument E is a logical expression.
10217 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10218   ::CheckBoolLikeConversion(*this, E, CC);
10219 }
10220 
10221 /// Diagnose when expression is an integer constant expression and its evaluation
10222 /// results in integer overflow
10223 void Sema::CheckForIntOverflow (Expr *E) {
10224   // Use a work list to deal with nested struct initializers.
10225   SmallVector<Expr *, 2> Exprs(1, E);
10226 
10227   do {
10228     Expr *OriginalE = Exprs.pop_back_val();
10229     Expr *E = OriginalE->IgnoreParenCasts();
10230 
10231     if (isa<BinaryOperator>(E)) {
10232       E->EvaluateForOverflow(Context);
10233       continue;
10234     }
10235 
10236     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
10237       Exprs.append(InitList->inits().begin(), InitList->inits().end());
10238     else if (isa<ObjCBoxedExpr>(OriginalE))
10239       E->EvaluateForOverflow(Context);
10240     else if (auto Call = dyn_cast<CallExpr>(E))
10241       Exprs.append(Call->arg_begin(), Call->arg_end());
10242     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
10243       Exprs.append(Message->arg_begin(), Message->arg_end());
10244   } while (!Exprs.empty());
10245 }
10246 
10247 namespace {
10248 
10249 /// \brief Visitor for expressions which looks for unsequenced operations on the
10250 /// same object.
10251 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10252   using Base = EvaluatedExprVisitor<SequenceChecker>;
10253 
10254   /// \brief A tree of sequenced regions within an expression. Two regions are
10255   /// unsequenced if one is an ancestor or a descendent of the other. When we
10256   /// finish processing an expression with sequencing, such as a comma
10257   /// expression, we fold its tree nodes into its parent, since they are
10258   /// unsequenced with respect to nodes we will visit later.
10259   class SequenceTree {
10260     struct Value {
10261       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10262       unsigned Parent : 31;
10263       unsigned Merged : 1;
10264     };
10265     SmallVector<Value, 8> Values;
10266 
10267   public:
10268     /// \brief A region within an expression which may be sequenced with respect
10269     /// to some other region.
10270     class Seq {
10271       friend class SequenceTree;
10272 
10273       unsigned Index = 0;
10274 
10275       explicit Seq(unsigned N) : Index(N) {}
10276 
10277     public:
10278       Seq() = default;
10279     };
10280 
10281     SequenceTree() { Values.push_back(Value(0)); }
10282     Seq root() const { return Seq(0); }
10283 
10284     /// \brief Create a new sequence of operations, which is an unsequenced
10285     /// subset of \p Parent. This sequence of operations is sequenced with
10286     /// respect to other children of \p Parent.
10287     Seq allocate(Seq Parent) {
10288       Values.push_back(Value(Parent.Index));
10289       return Seq(Values.size() - 1);
10290     }
10291 
10292     /// \brief Merge a sequence of operations into its parent.
10293     void merge(Seq S) {
10294       Values[S.Index].Merged = true;
10295     }
10296 
10297     /// \brief Determine whether two operations are unsequenced. This operation
10298     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10299     /// should have been merged into its parent as appropriate.
10300     bool isUnsequenced(Seq Cur, Seq Old) {
10301       unsigned C = representative(Cur.Index);
10302       unsigned Target = representative(Old.Index);
10303       while (C >= Target) {
10304         if (C == Target)
10305           return true;
10306         C = Values[C].Parent;
10307       }
10308       return false;
10309     }
10310 
10311   private:
10312     /// \brief Pick a representative for a sequence.
10313     unsigned representative(unsigned K) {
10314       if (Values[K].Merged)
10315         // Perform path compression as we go.
10316         return Values[K].Parent = representative(Values[K].Parent);
10317       return K;
10318     }
10319   };
10320 
10321   /// An object for which we can track unsequenced uses.
10322   using Object = NamedDecl *;
10323 
10324   /// Different flavors of object usage which we track. We only track the
10325   /// least-sequenced usage of each kind.
10326   enum UsageKind {
10327     /// A read of an object. Multiple unsequenced reads are OK.
10328     UK_Use,
10329 
10330     /// A modification of an object which is sequenced before the value
10331     /// computation of the expression, such as ++n in C++.
10332     UK_ModAsValue,
10333 
10334     /// A modification of an object which is not sequenced before the value
10335     /// computation of the expression, such as n++.
10336     UK_ModAsSideEffect,
10337 
10338     UK_Count = UK_ModAsSideEffect + 1
10339   };
10340 
10341   struct Usage {
10342     Expr *Use = nullptr;
10343     SequenceTree::Seq Seq;
10344 
10345     Usage() = default;
10346   };
10347 
10348   struct UsageInfo {
10349     Usage Uses[UK_Count];
10350 
10351     /// Have we issued a diagnostic for this variable already?
10352     bool Diagnosed = false;
10353 
10354     UsageInfo() = default;
10355   };
10356   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
10357 
10358   Sema &SemaRef;
10359 
10360   /// Sequenced regions within the expression.
10361   SequenceTree Tree;
10362 
10363   /// Declaration modifications and references which we have seen.
10364   UsageInfoMap UsageMap;
10365 
10366   /// The region we are currently within.
10367   SequenceTree::Seq Region;
10368 
10369   /// Filled in with declarations which were modified as a side-effect
10370   /// (that is, post-increment operations).
10371   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10372 
10373   /// Expressions to check later. We defer checking these to reduce
10374   /// stack usage.
10375   SmallVectorImpl<Expr *> &WorkList;
10376 
10377   /// RAII object wrapping the visitation of a sequenced subexpression of an
10378   /// expression. At the end of this process, the side-effects of the evaluation
10379   /// become sequenced with respect to the value computation of the result, so
10380   /// we downgrade any UK_ModAsSideEffect within the evaluation to
10381   /// UK_ModAsValue.
10382   struct SequencedSubexpression {
10383     SequencedSubexpression(SequenceChecker &Self)
10384       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10385       Self.ModAsSideEffect = &ModAsSideEffect;
10386     }
10387 
10388     ~SequencedSubexpression() {
10389       for (auto &M : llvm::reverse(ModAsSideEffect)) {
10390         UsageInfo &U = Self.UsageMap[M.first];
10391         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10392         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10393         SideEffectUsage = M.second;
10394       }
10395       Self.ModAsSideEffect = OldModAsSideEffect;
10396     }
10397 
10398     SequenceChecker &Self;
10399     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10400     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
10401   };
10402 
10403   /// RAII object wrapping the visitation of a subexpression which we might
10404   /// choose to evaluate as a constant. If any subexpression is evaluated and
10405   /// found to be non-constant, this allows us to suppress the evaluation of
10406   /// the outer expression.
10407   class EvaluationTracker {
10408   public:
10409     EvaluationTracker(SequenceChecker &Self)
10410         : Self(Self), Prev(Self.EvalTracker) {
10411       Self.EvalTracker = this;
10412     }
10413 
10414     ~EvaluationTracker() {
10415       Self.EvalTracker = Prev;
10416       if (Prev)
10417         Prev->EvalOK &= EvalOK;
10418     }
10419 
10420     bool evaluate(const Expr *E, bool &Result) {
10421       if (!EvalOK || E->isValueDependent())
10422         return false;
10423       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10424       return EvalOK;
10425     }
10426 
10427   private:
10428     SequenceChecker &Self;
10429     EvaluationTracker *Prev;
10430     bool EvalOK = true;
10431   } *EvalTracker = nullptr;
10432 
10433   /// \brief Find the object which is produced by the specified expression,
10434   /// if any.
10435   Object getObject(Expr *E, bool Mod) const {
10436     E = E->IgnoreParenCasts();
10437     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10438       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10439         return getObject(UO->getSubExpr(), Mod);
10440     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10441       if (BO->getOpcode() == BO_Comma)
10442         return getObject(BO->getRHS(), Mod);
10443       if (Mod && BO->isAssignmentOp())
10444         return getObject(BO->getLHS(), Mod);
10445     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10446       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10447       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10448         return ME->getMemberDecl();
10449     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10450       // FIXME: If this is a reference, map through to its value.
10451       return DRE->getDecl();
10452     return nullptr;
10453   }
10454 
10455   /// \brief Note that an object was modified or used by an expression.
10456   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10457     Usage &U = UI.Uses[UK];
10458     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10459       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10460         ModAsSideEffect->push_back(std::make_pair(O, U));
10461       U.Use = Ref;
10462       U.Seq = Region;
10463     }
10464   }
10465 
10466   /// \brief Check whether a modification or use conflicts with a prior usage.
10467   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10468                   bool IsModMod) {
10469     if (UI.Diagnosed)
10470       return;
10471 
10472     const Usage &U = UI.Uses[OtherKind];
10473     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10474       return;
10475 
10476     Expr *Mod = U.Use;
10477     Expr *ModOrUse = Ref;
10478     if (OtherKind == UK_Use)
10479       std::swap(Mod, ModOrUse);
10480 
10481     SemaRef.Diag(Mod->getExprLoc(),
10482                  IsModMod ? diag::warn_unsequenced_mod_mod
10483                           : diag::warn_unsequenced_mod_use)
10484       << O << SourceRange(ModOrUse->getExprLoc());
10485     UI.Diagnosed = true;
10486   }
10487 
10488   void notePreUse(Object O, Expr *Use) {
10489     UsageInfo &U = UsageMap[O];
10490     // Uses conflict with other modifications.
10491     checkUsage(O, U, Use, UK_ModAsValue, false);
10492   }
10493 
10494   void notePostUse(Object O, Expr *Use) {
10495     UsageInfo &U = UsageMap[O];
10496     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10497     addUsage(U, O, Use, UK_Use);
10498   }
10499 
10500   void notePreMod(Object O, Expr *Mod) {
10501     UsageInfo &U = UsageMap[O];
10502     // Modifications conflict with other modifications and with uses.
10503     checkUsage(O, U, Mod, UK_ModAsValue, true);
10504     checkUsage(O, U, Mod, UK_Use, false);
10505   }
10506 
10507   void notePostMod(Object O, Expr *Use, UsageKind UK) {
10508     UsageInfo &U = UsageMap[O];
10509     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10510     addUsage(U, O, Use, UK);
10511   }
10512 
10513 public:
10514   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10515       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
10516     Visit(E);
10517   }
10518 
10519   void VisitStmt(Stmt *S) {
10520     // Skip all statements which aren't expressions for now.
10521   }
10522 
10523   void VisitExpr(Expr *E) {
10524     // By default, just recurse to evaluated subexpressions.
10525     Base::VisitStmt(E);
10526   }
10527 
10528   void VisitCastExpr(CastExpr *E) {
10529     Object O = Object();
10530     if (E->getCastKind() == CK_LValueToRValue)
10531       O = getObject(E->getSubExpr(), false);
10532 
10533     if (O)
10534       notePreUse(O, E);
10535     VisitExpr(E);
10536     if (O)
10537       notePostUse(O, E);
10538   }
10539 
10540   void VisitBinComma(BinaryOperator *BO) {
10541     // C++11 [expr.comma]p1:
10542     //   Every value computation and side effect associated with the left
10543     //   expression is sequenced before every value computation and side
10544     //   effect associated with the right expression.
10545     SequenceTree::Seq LHS = Tree.allocate(Region);
10546     SequenceTree::Seq RHS = Tree.allocate(Region);
10547     SequenceTree::Seq OldRegion = Region;
10548 
10549     {
10550       SequencedSubexpression SeqLHS(*this);
10551       Region = LHS;
10552       Visit(BO->getLHS());
10553     }
10554 
10555     Region = RHS;
10556     Visit(BO->getRHS());
10557 
10558     Region = OldRegion;
10559 
10560     // Forget that LHS and RHS are sequenced. They are both unsequenced
10561     // with respect to other stuff.
10562     Tree.merge(LHS);
10563     Tree.merge(RHS);
10564   }
10565 
10566   void VisitBinAssign(BinaryOperator *BO) {
10567     // The modification is sequenced after the value computation of the LHS
10568     // and RHS, so check it before inspecting the operands and update the
10569     // map afterwards.
10570     Object O = getObject(BO->getLHS(), true);
10571     if (!O)
10572       return VisitExpr(BO);
10573 
10574     notePreMod(O, BO);
10575 
10576     // C++11 [expr.ass]p7:
10577     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10578     //   only once.
10579     //
10580     // Therefore, for a compound assignment operator, O is considered used
10581     // everywhere except within the evaluation of E1 itself.
10582     if (isa<CompoundAssignOperator>(BO))
10583       notePreUse(O, BO);
10584 
10585     Visit(BO->getLHS());
10586 
10587     if (isa<CompoundAssignOperator>(BO))
10588       notePostUse(O, BO);
10589 
10590     Visit(BO->getRHS());
10591 
10592     // C++11 [expr.ass]p1:
10593     //   the assignment is sequenced [...] before the value computation of the
10594     //   assignment expression.
10595     // C11 6.5.16/3 has no such rule.
10596     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10597                                                        : UK_ModAsSideEffect);
10598   }
10599 
10600   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10601     VisitBinAssign(CAO);
10602   }
10603 
10604   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10605   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10606   void VisitUnaryPreIncDec(UnaryOperator *UO) {
10607     Object O = getObject(UO->getSubExpr(), true);
10608     if (!O)
10609       return VisitExpr(UO);
10610 
10611     notePreMod(O, UO);
10612     Visit(UO->getSubExpr());
10613     // C++11 [expr.pre.incr]p1:
10614     //   the expression ++x is equivalent to x+=1
10615     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10616                                                        : UK_ModAsSideEffect);
10617   }
10618 
10619   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10620   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10621   void VisitUnaryPostIncDec(UnaryOperator *UO) {
10622     Object O = getObject(UO->getSubExpr(), true);
10623     if (!O)
10624       return VisitExpr(UO);
10625 
10626     notePreMod(O, UO);
10627     Visit(UO->getSubExpr());
10628     notePostMod(O, UO, UK_ModAsSideEffect);
10629   }
10630 
10631   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10632   void VisitBinLOr(BinaryOperator *BO) {
10633     // The side-effects of the LHS of an '&&' are sequenced before the
10634     // value computation of the RHS, and hence before the value computation
10635     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10636     // as if they were unconditionally sequenced.
10637     EvaluationTracker Eval(*this);
10638     {
10639       SequencedSubexpression Sequenced(*this);
10640       Visit(BO->getLHS());
10641     }
10642 
10643     bool Result;
10644     if (Eval.evaluate(BO->getLHS(), Result)) {
10645       if (!Result)
10646         Visit(BO->getRHS());
10647     } else {
10648       // Check for unsequenced operations in the RHS, treating it as an
10649       // entirely separate evaluation.
10650       //
10651       // FIXME: If there are operations in the RHS which are unsequenced
10652       // with respect to operations outside the RHS, and those operations
10653       // are unconditionally evaluated, diagnose them.
10654       WorkList.push_back(BO->getRHS());
10655     }
10656   }
10657   void VisitBinLAnd(BinaryOperator *BO) {
10658     EvaluationTracker Eval(*this);
10659     {
10660       SequencedSubexpression Sequenced(*this);
10661       Visit(BO->getLHS());
10662     }
10663 
10664     bool Result;
10665     if (Eval.evaluate(BO->getLHS(), Result)) {
10666       if (Result)
10667         Visit(BO->getRHS());
10668     } else {
10669       WorkList.push_back(BO->getRHS());
10670     }
10671   }
10672 
10673   // Only visit the condition, unless we can be sure which subexpression will
10674   // be chosen.
10675   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10676     EvaluationTracker Eval(*this);
10677     {
10678       SequencedSubexpression Sequenced(*this);
10679       Visit(CO->getCond());
10680     }
10681 
10682     bool Result;
10683     if (Eval.evaluate(CO->getCond(), Result))
10684       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10685     else {
10686       WorkList.push_back(CO->getTrueExpr());
10687       WorkList.push_back(CO->getFalseExpr());
10688     }
10689   }
10690 
10691   void VisitCallExpr(CallExpr *CE) {
10692     // C++11 [intro.execution]p15:
10693     //   When calling a function [...], every value computation and side effect
10694     //   associated with any argument expression, or with the postfix expression
10695     //   designating the called function, is sequenced before execution of every
10696     //   expression or statement in the body of the function [and thus before
10697     //   the value computation of its result].
10698     SequencedSubexpression Sequenced(*this);
10699     Base::VisitCallExpr(CE);
10700 
10701     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10702   }
10703 
10704   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10705     // This is a call, so all subexpressions are sequenced before the result.
10706     SequencedSubexpression Sequenced(*this);
10707 
10708     if (!CCE->isListInitialization())
10709       return VisitExpr(CCE);
10710 
10711     // In C++11, list initializations are sequenced.
10712     SmallVector<SequenceTree::Seq, 32> Elts;
10713     SequenceTree::Seq Parent = Region;
10714     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10715                                         E = CCE->arg_end();
10716          I != E; ++I) {
10717       Region = Tree.allocate(Parent);
10718       Elts.push_back(Region);
10719       Visit(*I);
10720     }
10721 
10722     // Forget that the initializers are sequenced.
10723     Region = Parent;
10724     for (unsigned I = 0; I < Elts.size(); ++I)
10725       Tree.merge(Elts[I]);
10726   }
10727 
10728   void VisitInitListExpr(InitListExpr *ILE) {
10729     if (!SemaRef.getLangOpts().CPlusPlus11)
10730       return VisitExpr(ILE);
10731 
10732     // In C++11, list initializations are sequenced.
10733     SmallVector<SequenceTree::Seq, 32> Elts;
10734     SequenceTree::Seq Parent = Region;
10735     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10736       Expr *E = ILE->getInit(I);
10737       if (!E) continue;
10738       Region = Tree.allocate(Parent);
10739       Elts.push_back(Region);
10740       Visit(E);
10741     }
10742 
10743     // Forget that the initializers are sequenced.
10744     Region = Parent;
10745     for (unsigned I = 0; I < Elts.size(); ++I)
10746       Tree.merge(Elts[I]);
10747   }
10748 };
10749 
10750 } // namespace
10751 
10752 void Sema::CheckUnsequencedOperations(Expr *E) {
10753   SmallVector<Expr *, 8> WorkList;
10754   WorkList.push_back(E);
10755   while (!WorkList.empty()) {
10756     Expr *Item = WorkList.pop_back_val();
10757     SequenceChecker(*this, Item, WorkList);
10758   }
10759 }
10760 
10761 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10762                               bool IsConstexpr) {
10763   CheckImplicitConversions(E, CheckLoc);
10764   if (!E->isInstantiationDependent())
10765     CheckUnsequencedOperations(E);
10766   if (!IsConstexpr && !E->isValueDependent())
10767     CheckForIntOverflow(E);
10768   DiagnoseMisalignedMembers();
10769 }
10770 
10771 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10772                                        FieldDecl *BitField,
10773                                        Expr *Init) {
10774   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10775 }
10776 
10777 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10778                                          SourceLocation Loc) {
10779   if (!PType->isVariablyModifiedType())
10780     return;
10781   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10782     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10783     return;
10784   }
10785   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10786     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10787     return;
10788   }
10789   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10790     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10791     return;
10792   }
10793 
10794   const ArrayType *AT = S.Context.getAsArrayType(PType);
10795   if (!AT)
10796     return;
10797 
10798   if (AT->getSizeModifier() != ArrayType::Star) {
10799     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10800     return;
10801   }
10802 
10803   S.Diag(Loc, diag::err_array_star_in_function_definition);
10804 }
10805 
10806 /// CheckParmsForFunctionDef - Check that the parameters of the given
10807 /// function are appropriate for the definition of a function. This
10808 /// takes care of any checks that cannot be performed on the
10809 /// declaration itself, e.g., that the types of each of the function
10810 /// parameters are complete.
10811 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10812                                     bool CheckParameterNames) {
10813   bool HasInvalidParm = false;
10814   for (ParmVarDecl *Param : Parameters) {
10815     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10816     // function declarator that is part of a function definition of
10817     // that function shall not have incomplete type.
10818     //
10819     // This is also C++ [dcl.fct]p6.
10820     if (!Param->isInvalidDecl() &&
10821         RequireCompleteType(Param->getLocation(), Param->getType(),
10822                             diag::err_typecheck_decl_incomplete_type)) {
10823       Param->setInvalidDecl();
10824       HasInvalidParm = true;
10825     }
10826 
10827     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10828     // declaration of each parameter shall include an identifier.
10829     if (CheckParameterNames &&
10830         Param->getIdentifier() == nullptr &&
10831         !Param->isImplicit() &&
10832         !getLangOpts().CPlusPlus)
10833       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10834 
10835     // C99 6.7.5.3p12:
10836     //   If the function declarator is not part of a definition of that
10837     //   function, parameters may have incomplete type and may use the [*]
10838     //   notation in their sequences of declarator specifiers to specify
10839     //   variable length array types.
10840     QualType PType = Param->getOriginalType();
10841     // FIXME: This diagnostic should point the '[*]' if source-location
10842     // information is added for it.
10843     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10844 
10845     // If the parameter is a c++ class type and it has to be destructed in the
10846     // callee function, declare the destructor so that it can be called by the
10847     // callee function. Do not perfom any direct access check on the dtor here.
10848     if (!Param->isInvalidDecl()) {
10849       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
10850         if (!ClassDecl->isInvalidDecl() &&
10851             !ClassDecl->hasIrrelevantDestructor() &&
10852             !ClassDecl->isDependentContext() &&
10853             Context.isParamDestroyedInCallee(Param->getType())) {
10854           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10855           MarkFunctionReferenced(Param->getLocation(), Destructor);
10856           DiagnoseUseOfDecl(Destructor, Param->getLocation());
10857         }
10858       }
10859     }
10860 
10861     // Parameters with the pass_object_size attribute only need to be marked
10862     // constant at function definitions. Because we lack information about
10863     // whether we're on a declaration or definition when we're instantiating the
10864     // attribute, we need to check for constness here.
10865     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10866       if (!Param->getType().isConstQualified())
10867         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10868             << Attr->getSpelling() << 1;
10869   }
10870 
10871   return HasInvalidParm;
10872 }
10873 
10874 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10875 /// or MemberExpr.
10876 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10877                               ASTContext &Context) {
10878   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10879     return Context.getDeclAlign(DRE->getDecl());
10880 
10881   if (const auto *ME = dyn_cast<MemberExpr>(E))
10882     return Context.getDeclAlign(ME->getMemberDecl());
10883 
10884   return TypeAlign;
10885 }
10886 
10887 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10888 /// pointer cast increases the alignment requirements.
10889 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10890   // This is actually a lot of work to potentially be doing on every
10891   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10892   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10893     return;
10894 
10895   // Ignore dependent types.
10896   if (T->isDependentType() || Op->getType()->isDependentType())
10897     return;
10898 
10899   // Require that the destination be a pointer type.
10900   const PointerType *DestPtr = T->getAs<PointerType>();
10901   if (!DestPtr) return;
10902 
10903   // If the destination has alignment 1, we're done.
10904   QualType DestPointee = DestPtr->getPointeeType();
10905   if (DestPointee->isIncompleteType()) return;
10906   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10907   if (DestAlign.isOne()) return;
10908 
10909   // Require that the source be a pointer type.
10910   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10911   if (!SrcPtr) return;
10912   QualType SrcPointee = SrcPtr->getPointeeType();
10913 
10914   // Whitelist casts from cv void*.  We already implicitly
10915   // whitelisted casts to cv void*, since they have alignment 1.
10916   // Also whitelist casts involving incomplete types, which implicitly
10917   // includes 'void'.
10918   if (SrcPointee->isIncompleteType()) return;
10919 
10920   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10921 
10922   if (auto *CE = dyn_cast<CastExpr>(Op)) {
10923     if (CE->getCastKind() == CK_ArrayToPointerDecay)
10924       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10925   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10926     if (UO->getOpcode() == UO_AddrOf)
10927       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10928   }
10929 
10930   if (SrcAlign >= DestAlign) return;
10931 
10932   Diag(TRange.getBegin(), diag::warn_cast_align)
10933     << Op->getType() << T
10934     << static_cast<unsigned>(SrcAlign.getQuantity())
10935     << static_cast<unsigned>(DestAlign.getQuantity())
10936     << TRange << Op->getSourceRange();
10937 }
10938 
10939 /// \brief Check whether this array fits the idiom of a size-one tail padded
10940 /// array member of a struct.
10941 ///
10942 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10943 /// commonly used to emulate flexible arrays in C89 code.
10944 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10945                                     const NamedDecl *ND) {
10946   if (Size != 1 || !ND) return false;
10947 
10948   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10949   if (!FD) return false;
10950 
10951   // Don't consider sizes resulting from macro expansions or template argument
10952   // substitution to form C89 tail-padded arrays.
10953 
10954   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10955   while (TInfo) {
10956     TypeLoc TL = TInfo->getTypeLoc();
10957     // Look through typedefs.
10958     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10959       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10960       TInfo = TDL->getTypeSourceInfo();
10961       continue;
10962     }
10963     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10964       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10965       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10966         return false;
10967     }
10968     break;
10969   }
10970 
10971   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10972   if (!RD) return false;
10973   if (RD->isUnion()) return false;
10974   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10975     if (!CRD->isStandardLayout()) return false;
10976   }
10977 
10978   // See if this is the last field decl in the record.
10979   const Decl *D = FD;
10980   while ((D = D->getNextDeclInContext()))
10981     if (isa<FieldDecl>(D))
10982       return false;
10983   return true;
10984 }
10985 
10986 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10987                             const ArraySubscriptExpr *ASE,
10988                             bool AllowOnePastEnd, bool IndexNegated) {
10989   IndexExpr = IndexExpr->IgnoreParenImpCasts();
10990   if (IndexExpr->isValueDependent())
10991     return;
10992 
10993   const Type *EffectiveType =
10994       BaseExpr->getType()->getPointeeOrArrayElementType();
10995   BaseExpr = BaseExpr->IgnoreParenCasts();
10996   const ConstantArrayType *ArrayTy =
10997     Context.getAsConstantArrayType(BaseExpr->getType());
10998   if (!ArrayTy)
10999     return;
11000 
11001   llvm::APSInt index;
11002   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
11003     return;
11004   if (IndexNegated)
11005     index = -index;
11006 
11007   const NamedDecl *ND = nullptr;
11008   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11009     ND = DRE->getDecl();
11010   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11011     ND = ME->getMemberDecl();
11012 
11013   if (index.isUnsigned() || !index.isNegative()) {
11014     llvm::APInt size = ArrayTy->getSize();
11015     if (!size.isStrictlyPositive())
11016       return;
11017 
11018     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
11019     if (BaseType != EffectiveType) {
11020       // Make sure we're comparing apples to apples when comparing index to size
11021       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11022       uint64_t array_typesize = Context.getTypeSize(BaseType);
11023       // Handle ptrarith_typesize being zero, such as when casting to void*
11024       if (!ptrarith_typesize) ptrarith_typesize = 1;
11025       if (ptrarith_typesize != array_typesize) {
11026         // There's a cast to a different size type involved
11027         uint64_t ratio = array_typesize / ptrarith_typesize;
11028         // TODO: Be smarter about handling cases where array_typesize is not a
11029         // multiple of ptrarith_typesize
11030         if (ptrarith_typesize * ratio == array_typesize)
11031           size *= llvm::APInt(size.getBitWidth(), ratio);
11032       }
11033     }
11034 
11035     if (size.getBitWidth() > index.getBitWidth())
11036       index = index.zext(size.getBitWidth());
11037     else if (size.getBitWidth() < index.getBitWidth())
11038       size = size.zext(index.getBitWidth());
11039 
11040     // For array subscripting the index must be less than size, but for pointer
11041     // arithmetic also allow the index (offset) to be equal to size since
11042     // computing the next address after the end of the array is legal and
11043     // commonly done e.g. in C++ iterators and range-based for loops.
11044     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11045       return;
11046 
11047     // Also don't warn for arrays of size 1 which are members of some
11048     // structure. These are often used to approximate flexible arrays in C89
11049     // code.
11050     if (IsTailPaddedMemberArray(*this, size, ND))
11051       return;
11052 
11053     // Suppress the warning if the subscript expression (as identified by the
11054     // ']' location) and the index expression are both from macro expansions
11055     // within a system header.
11056     if (ASE) {
11057       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11058           ASE->getRBracketLoc());
11059       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11060         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11061             IndexExpr->getLocStart());
11062         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11063           return;
11064       }
11065     }
11066 
11067     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11068     if (ASE)
11069       DiagID = diag::warn_array_index_exceeds_bounds;
11070 
11071     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11072                         PDiag(DiagID) << index.toString(10, true)
11073                           << size.toString(10, true)
11074                           << (unsigned)size.getLimitedValue(~0U)
11075                           << IndexExpr->getSourceRange());
11076   } else {
11077     unsigned DiagID = diag::warn_array_index_precedes_bounds;
11078     if (!ASE) {
11079       DiagID = diag::warn_ptr_arith_precedes_bounds;
11080       if (index.isNegative()) index = -index;
11081     }
11082 
11083     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11084                         PDiag(DiagID) << index.toString(10, true)
11085                           << IndexExpr->getSourceRange());
11086   }
11087 
11088   if (!ND) {
11089     // Try harder to find a NamedDecl to point at in the note.
11090     while (const ArraySubscriptExpr *ASE =
11091            dyn_cast<ArraySubscriptExpr>(BaseExpr))
11092       BaseExpr = ASE->getBase()->IgnoreParenCasts();
11093     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11094       ND = DRE->getDecl();
11095     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11096       ND = ME->getMemberDecl();
11097   }
11098 
11099   if (ND)
11100     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11101                         PDiag(diag::note_array_index_out_of_bounds)
11102                           << ND->getDeclName());
11103 }
11104 
11105 void Sema::CheckArrayAccess(const Expr *expr) {
11106   int AllowOnePastEnd = 0;
11107   while (expr) {
11108     expr = expr->IgnoreParenImpCasts();
11109     switch (expr->getStmtClass()) {
11110       case Stmt::ArraySubscriptExprClass: {
11111         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11112         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11113                          AllowOnePastEnd > 0);
11114         return;
11115       }
11116       case Stmt::OMPArraySectionExprClass: {
11117         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11118         if (ASE->getLowerBound())
11119           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11120                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
11121         return;
11122       }
11123       case Stmt::UnaryOperatorClass: {
11124         // Only unwrap the * and & unary operators
11125         const UnaryOperator *UO = cast<UnaryOperator>(expr);
11126         expr = UO->getSubExpr();
11127         switch (UO->getOpcode()) {
11128           case UO_AddrOf:
11129             AllowOnePastEnd++;
11130             break;
11131           case UO_Deref:
11132             AllowOnePastEnd--;
11133             break;
11134           default:
11135             return;
11136         }
11137         break;
11138       }
11139       case Stmt::ConditionalOperatorClass: {
11140         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11141         if (const Expr *lhs = cond->getLHS())
11142           CheckArrayAccess(lhs);
11143         if (const Expr *rhs = cond->getRHS())
11144           CheckArrayAccess(rhs);
11145         return;
11146       }
11147       case Stmt::CXXOperatorCallExprClass: {
11148         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11149         for (const auto *Arg : OCE->arguments())
11150           CheckArrayAccess(Arg);
11151         return;
11152       }
11153       default:
11154         return;
11155     }
11156   }
11157 }
11158 
11159 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11160 
11161 namespace {
11162 
11163 struct RetainCycleOwner {
11164   VarDecl *Variable = nullptr;
11165   SourceRange Range;
11166   SourceLocation Loc;
11167   bool Indirect = false;
11168 
11169   RetainCycleOwner() = default;
11170 
11171   void setLocsFrom(Expr *e) {
11172     Loc = e->getExprLoc();
11173     Range = e->getSourceRange();
11174   }
11175 };
11176 
11177 } // namespace
11178 
11179 /// Consider whether capturing the given variable can possibly lead to
11180 /// a retain cycle.
11181 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11182   // In ARC, it's captured strongly iff the variable has __strong
11183   // lifetime.  In MRR, it's captured strongly if the variable is
11184   // __block and has an appropriate type.
11185   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11186     return false;
11187 
11188   owner.Variable = var;
11189   if (ref)
11190     owner.setLocsFrom(ref);
11191   return true;
11192 }
11193 
11194 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11195   while (true) {
11196     e = e->IgnoreParens();
11197     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11198       switch (cast->getCastKind()) {
11199       case CK_BitCast:
11200       case CK_LValueBitCast:
11201       case CK_LValueToRValue:
11202       case CK_ARCReclaimReturnedObject:
11203         e = cast->getSubExpr();
11204         continue;
11205 
11206       default:
11207         return false;
11208       }
11209     }
11210 
11211     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11212       ObjCIvarDecl *ivar = ref->getDecl();
11213       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11214         return false;
11215 
11216       // Try to find a retain cycle in the base.
11217       if (!findRetainCycleOwner(S, ref->getBase(), owner))
11218         return false;
11219 
11220       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11221       owner.Indirect = true;
11222       return true;
11223     }
11224 
11225     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11226       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11227       if (!var) return false;
11228       return considerVariable(var, ref, owner);
11229     }
11230 
11231     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11232       if (member->isArrow()) return false;
11233 
11234       // Don't count this as an indirect ownership.
11235       e = member->getBase();
11236       continue;
11237     }
11238 
11239     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11240       // Only pay attention to pseudo-objects on property references.
11241       ObjCPropertyRefExpr *pre
11242         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11243                                               ->IgnoreParens());
11244       if (!pre) return false;
11245       if (pre->isImplicitProperty()) return false;
11246       ObjCPropertyDecl *property = pre->getExplicitProperty();
11247       if (!property->isRetaining() &&
11248           !(property->getPropertyIvarDecl() &&
11249             property->getPropertyIvarDecl()->getType()
11250               .getObjCLifetime() == Qualifiers::OCL_Strong))
11251           return false;
11252 
11253       owner.Indirect = true;
11254       if (pre->isSuperReceiver()) {
11255         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11256         if (!owner.Variable)
11257           return false;
11258         owner.Loc = pre->getLocation();
11259         owner.Range = pre->getSourceRange();
11260         return true;
11261       }
11262       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11263                               ->getSourceExpr());
11264       continue;
11265     }
11266 
11267     // Array ivars?
11268 
11269     return false;
11270   }
11271 }
11272 
11273 namespace {
11274 
11275   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11276     ASTContext &Context;
11277     VarDecl *Variable;
11278     Expr *Capturer = nullptr;
11279     bool VarWillBeReased = false;
11280 
11281     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11282         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11283           Context(Context), Variable(variable) {}
11284 
11285     void VisitDeclRefExpr(DeclRefExpr *ref) {
11286       if (ref->getDecl() == Variable && !Capturer)
11287         Capturer = ref;
11288     }
11289 
11290     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11291       if (Capturer) return;
11292       Visit(ref->getBase());
11293       if (Capturer && ref->isFreeIvar())
11294         Capturer = ref;
11295     }
11296 
11297     void VisitBlockExpr(BlockExpr *block) {
11298       // Look inside nested blocks
11299       if (block->getBlockDecl()->capturesVariable(Variable))
11300         Visit(block->getBlockDecl()->getBody());
11301     }
11302 
11303     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11304       if (Capturer) return;
11305       if (OVE->getSourceExpr())
11306         Visit(OVE->getSourceExpr());
11307     }
11308 
11309     void VisitBinaryOperator(BinaryOperator *BinOp) {
11310       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11311         return;
11312       Expr *LHS = BinOp->getLHS();
11313       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11314         if (DRE->getDecl() != Variable)
11315           return;
11316         if (Expr *RHS = BinOp->getRHS()) {
11317           RHS = RHS->IgnoreParenCasts();
11318           llvm::APSInt Value;
11319           VarWillBeReased =
11320             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11321         }
11322       }
11323     }
11324   };
11325 
11326 } // namespace
11327 
11328 /// Check whether the given argument is a block which captures a
11329 /// variable.
11330 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11331   assert(owner.Variable && owner.Loc.isValid());
11332 
11333   e = e->IgnoreParenCasts();
11334 
11335   // Look through [^{...} copy] and Block_copy(^{...}).
11336   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11337     Selector Cmd = ME->getSelector();
11338     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11339       e = ME->getInstanceReceiver();
11340       if (!e)
11341         return nullptr;
11342       e = e->IgnoreParenCasts();
11343     }
11344   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11345     if (CE->getNumArgs() == 1) {
11346       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11347       if (Fn) {
11348         const IdentifierInfo *FnI = Fn->getIdentifier();
11349         if (FnI && FnI->isStr("_Block_copy")) {
11350           e = CE->getArg(0)->IgnoreParenCasts();
11351         }
11352       }
11353     }
11354   }
11355 
11356   BlockExpr *block = dyn_cast<BlockExpr>(e);
11357   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11358     return nullptr;
11359 
11360   FindCaptureVisitor visitor(S.Context, owner.Variable);
11361   visitor.Visit(block->getBlockDecl()->getBody());
11362   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11363 }
11364 
11365 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11366                                 RetainCycleOwner &owner) {
11367   assert(capturer);
11368   assert(owner.Variable && owner.Loc.isValid());
11369 
11370   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11371     << owner.Variable << capturer->getSourceRange();
11372   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11373     << owner.Indirect << owner.Range;
11374 }
11375 
11376 /// Check for a keyword selector that starts with the word 'add' or
11377 /// 'set'.
11378 static bool isSetterLikeSelector(Selector sel) {
11379   if (sel.isUnarySelector()) return false;
11380 
11381   StringRef str = sel.getNameForSlot(0);
11382   while (!str.empty() && str.front() == '_') str = str.substr(1);
11383   if (str.startswith("set"))
11384     str = str.substr(3);
11385   else if (str.startswith("add")) {
11386     // Specially whitelist 'addOperationWithBlock:'.
11387     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11388       return false;
11389     str = str.substr(3);
11390   }
11391   else
11392     return false;
11393 
11394   if (str.empty()) return true;
11395   return !isLowercase(str.front());
11396 }
11397 
11398 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11399                                                     ObjCMessageExpr *Message) {
11400   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11401                                                 Message->getReceiverInterface(),
11402                                                 NSAPI::ClassId_NSMutableArray);
11403   if (!IsMutableArray) {
11404     return None;
11405   }
11406 
11407   Selector Sel = Message->getSelector();
11408 
11409   Optional<NSAPI::NSArrayMethodKind> MKOpt =
11410     S.NSAPIObj->getNSArrayMethodKind(Sel);
11411   if (!MKOpt) {
11412     return None;
11413   }
11414 
11415   NSAPI::NSArrayMethodKind MK = *MKOpt;
11416 
11417   switch (MK) {
11418     case NSAPI::NSMutableArr_addObject:
11419     case NSAPI::NSMutableArr_insertObjectAtIndex:
11420     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11421       return 0;
11422     case NSAPI::NSMutableArr_replaceObjectAtIndex:
11423       return 1;
11424 
11425     default:
11426       return None;
11427   }
11428 
11429   return None;
11430 }
11431 
11432 static
11433 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11434                                                   ObjCMessageExpr *Message) {
11435   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11436                                             Message->getReceiverInterface(),
11437                                             NSAPI::ClassId_NSMutableDictionary);
11438   if (!IsMutableDictionary) {
11439     return None;
11440   }
11441 
11442   Selector Sel = Message->getSelector();
11443 
11444   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11445     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11446   if (!MKOpt) {
11447     return None;
11448   }
11449 
11450   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11451 
11452   switch (MK) {
11453     case NSAPI::NSMutableDict_setObjectForKey:
11454     case NSAPI::NSMutableDict_setValueForKey:
11455     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11456       return 0;
11457 
11458     default:
11459       return None;
11460   }
11461 
11462   return None;
11463 }
11464 
11465 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11466   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11467                                                 Message->getReceiverInterface(),
11468                                                 NSAPI::ClassId_NSMutableSet);
11469 
11470   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11471                                             Message->getReceiverInterface(),
11472                                             NSAPI::ClassId_NSMutableOrderedSet);
11473   if (!IsMutableSet && !IsMutableOrderedSet) {
11474     return None;
11475   }
11476 
11477   Selector Sel = Message->getSelector();
11478 
11479   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11480   if (!MKOpt) {
11481     return None;
11482   }
11483 
11484   NSAPI::NSSetMethodKind MK = *MKOpt;
11485 
11486   switch (MK) {
11487     case NSAPI::NSMutableSet_addObject:
11488     case NSAPI::NSOrderedSet_setObjectAtIndex:
11489     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11490     case NSAPI::NSOrderedSet_insertObjectAtIndex:
11491       return 0;
11492     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11493       return 1;
11494   }
11495 
11496   return None;
11497 }
11498 
11499 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11500   if (!Message->isInstanceMessage()) {
11501     return;
11502   }
11503 
11504   Optional<int> ArgOpt;
11505 
11506   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11507       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11508       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11509     return;
11510   }
11511 
11512   int ArgIndex = *ArgOpt;
11513 
11514   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11515   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11516     Arg = OE->getSourceExpr()->IgnoreImpCasts();
11517   }
11518 
11519   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11520     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11521       if (ArgRE->isObjCSelfExpr()) {
11522         Diag(Message->getSourceRange().getBegin(),
11523              diag::warn_objc_circular_container)
11524           << ArgRE->getDecl() << StringRef("'super'");
11525       }
11526     }
11527   } else {
11528     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11529 
11530     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11531       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11532     }
11533 
11534     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11535       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11536         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11537           ValueDecl *Decl = ReceiverRE->getDecl();
11538           Diag(Message->getSourceRange().getBegin(),
11539                diag::warn_objc_circular_container)
11540             << Decl << Decl;
11541           if (!ArgRE->isObjCSelfExpr()) {
11542             Diag(Decl->getLocation(),
11543                  diag::note_objc_circular_container_declared_here)
11544               << Decl;
11545           }
11546         }
11547       }
11548     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11549       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11550         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11551           ObjCIvarDecl *Decl = IvarRE->getDecl();
11552           Diag(Message->getSourceRange().getBegin(),
11553                diag::warn_objc_circular_container)
11554             << Decl << Decl;
11555           Diag(Decl->getLocation(),
11556                diag::note_objc_circular_container_declared_here)
11557             << Decl;
11558         }
11559       }
11560     }
11561   }
11562 }
11563 
11564 /// Check a message send to see if it's likely to cause a retain cycle.
11565 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11566   // Only check instance methods whose selector looks like a setter.
11567   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11568     return;
11569 
11570   // Try to find a variable that the receiver is strongly owned by.
11571   RetainCycleOwner owner;
11572   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11573     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11574       return;
11575   } else {
11576     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11577     owner.Variable = getCurMethodDecl()->getSelfDecl();
11578     owner.Loc = msg->getSuperLoc();
11579     owner.Range = msg->getSuperLoc();
11580   }
11581 
11582   // Check whether the receiver is captured by any of the arguments.
11583   const ObjCMethodDecl *MD = msg->getMethodDecl();
11584   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11585     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11586       // noescape blocks should not be retained by the method.
11587       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11588         continue;
11589       return diagnoseRetainCycle(*this, capturer, owner);
11590     }
11591   }
11592 }
11593 
11594 /// Check a property assign to see if it's likely to cause a retain cycle.
11595 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11596   RetainCycleOwner owner;
11597   if (!findRetainCycleOwner(*this, receiver, owner))
11598     return;
11599 
11600   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11601     diagnoseRetainCycle(*this, capturer, owner);
11602 }
11603 
11604 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11605   RetainCycleOwner Owner;
11606   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11607     return;
11608 
11609   // Because we don't have an expression for the variable, we have to set the
11610   // location explicitly here.
11611   Owner.Loc = Var->getLocation();
11612   Owner.Range = Var->getSourceRange();
11613 
11614   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11615     diagnoseRetainCycle(*this, Capturer, Owner);
11616 }
11617 
11618 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11619                                      Expr *RHS, bool isProperty) {
11620   // Check if RHS is an Objective-C object literal, which also can get
11621   // immediately zapped in a weak reference.  Note that we explicitly
11622   // allow ObjCStringLiterals, since those are designed to never really die.
11623   RHS = RHS->IgnoreParenImpCasts();
11624 
11625   // This enum needs to match with the 'select' in
11626   // warn_objc_arc_literal_assign (off-by-1).
11627   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11628   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11629     return false;
11630 
11631   S.Diag(Loc, diag::warn_arc_literal_assign)
11632     << (unsigned) Kind
11633     << (isProperty ? 0 : 1)
11634     << RHS->getSourceRange();
11635 
11636   return true;
11637 }
11638 
11639 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11640                                     Qualifiers::ObjCLifetime LT,
11641                                     Expr *RHS, bool isProperty) {
11642   // Strip off any implicit cast added to get to the one ARC-specific.
11643   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11644     if (cast->getCastKind() == CK_ARCConsumeObject) {
11645       S.Diag(Loc, diag::warn_arc_retained_assign)
11646         << (LT == Qualifiers::OCL_ExplicitNone)
11647         << (isProperty ? 0 : 1)
11648         << RHS->getSourceRange();
11649       return true;
11650     }
11651     RHS = cast->getSubExpr();
11652   }
11653 
11654   if (LT == Qualifiers::OCL_Weak &&
11655       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11656     return true;
11657 
11658   return false;
11659 }
11660 
11661 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11662                               QualType LHS, Expr *RHS) {
11663   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11664 
11665   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11666     return false;
11667 
11668   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11669     return true;
11670 
11671   return false;
11672 }
11673 
11674 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11675                               Expr *LHS, Expr *RHS) {
11676   QualType LHSType;
11677   // PropertyRef on LHS type need be directly obtained from
11678   // its declaration as it has a PseudoType.
11679   ObjCPropertyRefExpr *PRE
11680     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11681   if (PRE && !PRE->isImplicitProperty()) {
11682     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11683     if (PD)
11684       LHSType = PD->getType();
11685   }
11686 
11687   if (LHSType.isNull())
11688     LHSType = LHS->getType();
11689 
11690   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11691 
11692   if (LT == Qualifiers::OCL_Weak) {
11693     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11694       getCurFunction()->markSafeWeakUse(LHS);
11695   }
11696 
11697   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11698     return;
11699 
11700   // FIXME. Check for other life times.
11701   if (LT != Qualifiers::OCL_None)
11702     return;
11703 
11704   if (PRE) {
11705     if (PRE->isImplicitProperty())
11706       return;
11707     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11708     if (!PD)
11709       return;
11710 
11711     unsigned Attributes = PD->getPropertyAttributes();
11712     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11713       // when 'assign' attribute was not explicitly specified
11714       // by user, ignore it and rely on property type itself
11715       // for lifetime info.
11716       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11717       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11718           LHSType->isObjCRetainableType())
11719         return;
11720 
11721       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11722         if (cast->getCastKind() == CK_ARCConsumeObject) {
11723           Diag(Loc, diag::warn_arc_retained_property_assign)
11724           << RHS->getSourceRange();
11725           return;
11726         }
11727         RHS = cast->getSubExpr();
11728       }
11729     }
11730     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11731       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11732         return;
11733     }
11734   }
11735 }
11736 
11737 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11738 
11739 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11740                                         SourceLocation StmtLoc,
11741                                         const NullStmt *Body) {
11742   // Do not warn if the body is a macro that expands to nothing, e.g:
11743   //
11744   // #define CALL(x)
11745   // if (condition)
11746   //   CALL(0);
11747   if (Body->hasLeadingEmptyMacro())
11748     return false;
11749 
11750   // Get line numbers of statement and body.
11751   bool StmtLineInvalid;
11752   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11753                                                       &StmtLineInvalid);
11754   if (StmtLineInvalid)
11755     return false;
11756 
11757   bool BodyLineInvalid;
11758   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11759                                                       &BodyLineInvalid);
11760   if (BodyLineInvalid)
11761     return false;
11762 
11763   // Warn if null statement and body are on the same line.
11764   if (StmtLine != BodyLine)
11765     return false;
11766 
11767   return true;
11768 }
11769 
11770 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11771                                  const Stmt *Body,
11772                                  unsigned DiagID) {
11773   // Since this is a syntactic check, don't emit diagnostic for template
11774   // instantiations, this just adds noise.
11775   if (CurrentInstantiationScope)
11776     return;
11777 
11778   // The body should be a null statement.
11779   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11780   if (!NBody)
11781     return;
11782 
11783   // Do the usual checks.
11784   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11785     return;
11786 
11787   Diag(NBody->getSemiLoc(), DiagID);
11788   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11789 }
11790 
11791 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11792                                  const Stmt *PossibleBody) {
11793   assert(!CurrentInstantiationScope); // Ensured by caller
11794 
11795   SourceLocation StmtLoc;
11796   const Stmt *Body;
11797   unsigned DiagID;
11798   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11799     StmtLoc = FS->getRParenLoc();
11800     Body = FS->getBody();
11801     DiagID = diag::warn_empty_for_body;
11802   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11803     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11804     Body = WS->getBody();
11805     DiagID = diag::warn_empty_while_body;
11806   } else
11807     return; // Neither `for' nor `while'.
11808 
11809   // The body should be a null statement.
11810   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11811   if (!NBody)
11812     return;
11813 
11814   // Skip expensive checks if diagnostic is disabled.
11815   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11816     return;
11817 
11818   // Do the usual checks.
11819   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11820     return;
11821 
11822   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11823   // noise level low, emit diagnostics only if for/while is followed by a
11824   // CompoundStmt, e.g.:
11825   //    for (int i = 0; i < n; i++);
11826   //    {
11827   //      a(i);
11828   //    }
11829   // or if for/while is followed by a statement with more indentation
11830   // than for/while itself:
11831   //    for (int i = 0; i < n; i++);
11832   //      a(i);
11833   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11834   if (!ProbableTypo) {
11835     bool BodyColInvalid;
11836     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11837                              PossibleBody->getLocStart(),
11838                              &BodyColInvalid);
11839     if (BodyColInvalid)
11840       return;
11841 
11842     bool StmtColInvalid;
11843     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11844                              S->getLocStart(),
11845                              &StmtColInvalid);
11846     if (StmtColInvalid)
11847       return;
11848 
11849     if (BodyCol > StmtCol)
11850       ProbableTypo = true;
11851   }
11852 
11853   if (ProbableTypo) {
11854     Diag(NBody->getSemiLoc(), DiagID);
11855     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11856   }
11857 }
11858 
11859 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11860 
11861 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11862 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11863                              SourceLocation OpLoc) {
11864   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11865     return;
11866 
11867   if (inTemplateInstantiation())
11868     return;
11869 
11870   // Strip parens and casts away.
11871   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11872   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11873 
11874   // Check for a call expression
11875   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11876   if (!CE || CE->getNumArgs() != 1)
11877     return;
11878 
11879   // Check for a call to std::move
11880   if (!CE->isCallToStdMove())
11881     return;
11882 
11883   // Get argument from std::move
11884   RHSExpr = CE->getArg(0);
11885 
11886   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11887   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11888 
11889   // Two DeclRefExpr's, check that the decls are the same.
11890   if (LHSDeclRef && RHSDeclRef) {
11891     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11892       return;
11893     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11894         RHSDeclRef->getDecl()->getCanonicalDecl())
11895       return;
11896 
11897     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11898                                         << LHSExpr->getSourceRange()
11899                                         << RHSExpr->getSourceRange();
11900     return;
11901   }
11902 
11903   // Member variables require a different approach to check for self moves.
11904   // MemberExpr's are the same if every nested MemberExpr refers to the same
11905   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11906   // the base Expr's are CXXThisExpr's.
11907   const Expr *LHSBase = LHSExpr;
11908   const Expr *RHSBase = RHSExpr;
11909   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11910   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11911   if (!LHSME || !RHSME)
11912     return;
11913 
11914   while (LHSME && RHSME) {
11915     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11916         RHSME->getMemberDecl()->getCanonicalDecl())
11917       return;
11918 
11919     LHSBase = LHSME->getBase();
11920     RHSBase = RHSME->getBase();
11921     LHSME = dyn_cast<MemberExpr>(LHSBase);
11922     RHSME = dyn_cast<MemberExpr>(RHSBase);
11923   }
11924 
11925   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11926   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11927   if (LHSDeclRef && RHSDeclRef) {
11928     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11929       return;
11930     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11931         RHSDeclRef->getDecl()->getCanonicalDecl())
11932       return;
11933 
11934     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11935                                         << LHSExpr->getSourceRange()
11936                                         << RHSExpr->getSourceRange();
11937     return;
11938   }
11939 
11940   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11941     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11942                                         << LHSExpr->getSourceRange()
11943                                         << RHSExpr->getSourceRange();
11944 }
11945 
11946 //===--- Layout compatibility ----------------------------------------------//
11947 
11948 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11949 
11950 /// \brief Check if two enumeration types are layout-compatible.
11951 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11952   // C++11 [dcl.enum] p8:
11953   // Two enumeration types are layout-compatible if they have the same
11954   // underlying type.
11955   return ED1->isComplete() && ED2->isComplete() &&
11956          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11957 }
11958 
11959 /// \brief Check if two fields are layout-compatible.
11960 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
11961                                FieldDecl *Field2) {
11962   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11963     return false;
11964 
11965   if (Field1->isBitField() != Field2->isBitField())
11966     return false;
11967 
11968   if (Field1->isBitField()) {
11969     // Make sure that the bit-fields are the same length.
11970     unsigned Bits1 = Field1->getBitWidthValue(C);
11971     unsigned Bits2 = Field2->getBitWidthValue(C);
11972 
11973     if (Bits1 != Bits2)
11974       return false;
11975   }
11976 
11977   return true;
11978 }
11979 
11980 /// \brief Check if two standard-layout structs are layout-compatible.
11981 /// (C++11 [class.mem] p17)
11982 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
11983                                      RecordDecl *RD2) {
11984   // If both records are C++ classes, check that base classes match.
11985   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11986     // If one of records is a CXXRecordDecl we are in C++ mode,
11987     // thus the other one is a CXXRecordDecl, too.
11988     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11989     // Check number of base classes.
11990     if (D1CXX->getNumBases() != D2CXX->getNumBases())
11991       return false;
11992 
11993     // Check the base classes.
11994     for (CXXRecordDecl::base_class_const_iterator
11995                Base1 = D1CXX->bases_begin(),
11996            BaseEnd1 = D1CXX->bases_end(),
11997               Base2 = D2CXX->bases_begin();
11998          Base1 != BaseEnd1;
11999          ++Base1, ++Base2) {
12000       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12001         return false;
12002     }
12003   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12004     // If only RD2 is a C++ class, it should have zero base classes.
12005     if (D2CXX->getNumBases() > 0)
12006       return false;
12007   }
12008 
12009   // Check the fields.
12010   RecordDecl::field_iterator Field2 = RD2->field_begin(),
12011                              Field2End = RD2->field_end(),
12012                              Field1 = RD1->field_begin(),
12013                              Field1End = RD1->field_end();
12014   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12015     if (!isLayoutCompatible(C, *Field1, *Field2))
12016       return false;
12017   }
12018   if (Field1 != Field1End || Field2 != Field2End)
12019     return false;
12020 
12021   return true;
12022 }
12023 
12024 /// \brief Check if two standard-layout unions are layout-compatible.
12025 /// (C++11 [class.mem] p18)
12026 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12027                                     RecordDecl *RD2) {
12028   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
12029   for (auto *Field2 : RD2->fields())
12030     UnmatchedFields.insert(Field2);
12031 
12032   for (auto *Field1 : RD1->fields()) {
12033     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12034         I = UnmatchedFields.begin(),
12035         E = UnmatchedFields.end();
12036 
12037     for ( ; I != E; ++I) {
12038       if (isLayoutCompatible(C, Field1, *I)) {
12039         bool Result = UnmatchedFields.erase(*I);
12040         (void) Result;
12041         assert(Result);
12042         break;
12043       }
12044     }
12045     if (I == E)
12046       return false;
12047   }
12048 
12049   return UnmatchedFields.empty();
12050 }
12051 
12052 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12053                                RecordDecl *RD2) {
12054   if (RD1->isUnion() != RD2->isUnion())
12055     return false;
12056 
12057   if (RD1->isUnion())
12058     return isLayoutCompatibleUnion(C, RD1, RD2);
12059   else
12060     return isLayoutCompatibleStruct(C, RD1, RD2);
12061 }
12062 
12063 /// \brief Check if two types are layout-compatible in C++11 sense.
12064 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12065   if (T1.isNull() || T2.isNull())
12066     return false;
12067 
12068   // C++11 [basic.types] p11:
12069   // If two types T1 and T2 are the same type, then T1 and T2 are
12070   // layout-compatible types.
12071   if (C.hasSameType(T1, T2))
12072     return true;
12073 
12074   T1 = T1.getCanonicalType().getUnqualifiedType();
12075   T2 = T2.getCanonicalType().getUnqualifiedType();
12076 
12077   const Type::TypeClass TC1 = T1->getTypeClass();
12078   const Type::TypeClass TC2 = T2->getTypeClass();
12079 
12080   if (TC1 != TC2)
12081     return false;
12082 
12083   if (TC1 == Type::Enum) {
12084     return isLayoutCompatible(C,
12085                               cast<EnumType>(T1)->getDecl(),
12086                               cast<EnumType>(T2)->getDecl());
12087   } else if (TC1 == Type::Record) {
12088     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12089       return false;
12090 
12091     return isLayoutCompatible(C,
12092                               cast<RecordType>(T1)->getDecl(),
12093                               cast<RecordType>(T2)->getDecl());
12094   }
12095 
12096   return false;
12097 }
12098 
12099 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12100 
12101 /// \brief Given a type tag expression find the type tag itself.
12102 ///
12103 /// \param TypeExpr Type tag expression, as it appears in user's code.
12104 ///
12105 /// \param VD Declaration of an identifier that appears in a type tag.
12106 ///
12107 /// \param MagicValue Type tag magic value.
12108 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12109                             const ValueDecl **VD, uint64_t *MagicValue) {
12110   while(true) {
12111     if (!TypeExpr)
12112       return false;
12113 
12114     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12115 
12116     switch (TypeExpr->getStmtClass()) {
12117     case Stmt::UnaryOperatorClass: {
12118       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12119       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12120         TypeExpr = UO->getSubExpr();
12121         continue;
12122       }
12123       return false;
12124     }
12125 
12126     case Stmt::DeclRefExprClass: {
12127       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12128       *VD = DRE->getDecl();
12129       return true;
12130     }
12131 
12132     case Stmt::IntegerLiteralClass: {
12133       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12134       llvm::APInt MagicValueAPInt = IL->getValue();
12135       if (MagicValueAPInt.getActiveBits() <= 64) {
12136         *MagicValue = MagicValueAPInt.getZExtValue();
12137         return true;
12138       } else
12139         return false;
12140     }
12141 
12142     case Stmt::BinaryConditionalOperatorClass:
12143     case Stmt::ConditionalOperatorClass: {
12144       const AbstractConditionalOperator *ACO =
12145           cast<AbstractConditionalOperator>(TypeExpr);
12146       bool Result;
12147       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12148         if (Result)
12149           TypeExpr = ACO->getTrueExpr();
12150         else
12151           TypeExpr = ACO->getFalseExpr();
12152         continue;
12153       }
12154       return false;
12155     }
12156 
12157     case Stmt::BinaryOperatorClass: {
12158       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12159       if (BO->getOpcode() == BO_Comma) {
12160         TypeExpr = BO->getRHS();
12161         continue;
12162       }
12163       return false;
12164     }
12165 
12166     default:
12167       return false;
12168     }
12169   }
12170 }
12171 
12172 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
12173 ///
12174 /// \param TypeExpr Expression that specifies a type tag.
12175 ///
12176 /// \param MagicValues Registered magic values.
12177 ///
12178 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12179 ///        kind.
12180 ///
12181 /// \param TypeInfo Information about the corresponding C type.
12182 ///
12183 /// \returns true if the corresponding C type was found.
12184 static bool GetMatchingCType(
12185         const IdentifierInfo *ArgumentKind,
12186         const Expr *TypeExpr, const ASTContext &Ctx,
12187         const llvm::DenseMap<Sema::TypeTagMagicValue,
12188                              Sema::TypeTagData> *MagicValues,
12189         bool &FoundWrongKind,
12190         Sema::TypeTagData &TypeInfo) {
12191   FoundWrongKind = false;
12192 
12193   // Variable declaration that has type_tag_for_datatype attribute.
12194   const ValueDecl *VD = nullptr;
12195 
12196   uint64_t MagicValue;
12197 
12198   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12199     return false;
12200 
12201   if (VD) {
12202     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12203       if (I->getArgumentKind() != ArgumentKind) {
12204         FoundWrongKind = true;
12205         return false;
12206       }
12207       TypeInfo.Type = I->getMatchingCType();
12208       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12209       TypeInfo.MustBeNull = I->getMustBeNull();
12210       return true;
12211     }
12212     return false;
12213   }
12214 
12215   if (!MagicValues)
12216     return false;
12217 
12218   llvm::DenseMap<Sema::TypeTagMagicValue,
12219                  Sema::TypeTagData>::const_iterator I =
12220       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12221   if (I == MagicValues->end())
12222     return false;
12223 
12224   TypeInfo = I->second;
12225   return true;
12226 }
12227 
12228 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12229                                       uint64_t MagicValue, QualType Type,
12230                                       bool LayoutCompatible,
12231                                       bool MustBeNull) {
12232   if (!TypeTagForDatatypeMagicValues)
12233     TypeTagForDatatypeMagicValues.reset(
12234         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12235 
12236   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12237   (*TypeTagForDatatypeMagicValues)[Magic] =
12238       TypeTagData(Type, LayoutCompatible, MustBeNull);
12239 }
12240 
12241 static bool IsSameCharType(QualType T1, QualType T2) {
12242   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12243   if (!BT1)
12244     return false;
12245 
12246   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12247   if (!BT2)
12248     return false;
12249 
12250   BuiltinType::Kind T1Kind = BT1->getKind();
12251   BuiltinType::Kind T2Kind = BT2->getKind();
12252 
12253   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
12254          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
12255          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12256          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12257 }
12258 
12259 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12260                                     const ArrayRef<const Expr *> ExprArgs,
12261                                     SourceLocation CallSiteLoc) {
12262   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12263   bool IsPointerAttr = Attr->getIsPointer();
12264 
12265   // Retrieve the argument representing the 'type_tag'.
12266   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
12267   if (TypeTagIdxAST >= ExprArgs.size()) {
12268     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12269         << 0 << Attr->getTypeTagIdx().getSourceIndex();
12270     return;
12271   }
12272   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
12273   bool FoundWrongKind;
12274   TypeTagData TypeInfo;
12275   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12276                         TypeTagForDatatypeMagicValues.get(),
12277                         FoundWrongKind, TypeInfo)) {
12278     if (FoundWrongKind)
12279       Diag(TypeTagExpr->getExprLoc(),
12280            diag::warn_type_tag_for_datatype_wrong_kind)
12281         << TypeTagExpr->getSourceRange();
12282     return;
12283   }
12284 
12285   // Retrieve the argument representing the 'arg_idx'.
12286   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
12287   if (ArgumentIdxAST >= ExprArgs.size()) {
12288     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12289         << 1 << Attr->getArgumentIdx().getSourceIndex();
12290     return;
12291   }
12292   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
12293   if (IsPointerAttr) {
12294     // Skip implicit cast of pointer to `void *' (as a function argument).
12295     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12296       if (ICE->getType()->isVoidPointerType() &&
12297           ICE->getCastKind() == CK_BitCast)
12298         ArgumentExpr = ICE->getSubExpr();
12299   }
12300   QualType ArgumentType = ArgumentExpr->getType();
12301 
12302   // Passing a `void*' pointer shouldn't trigger a warning.
12303   if (IsPointerAttr && ArgumentType->isVoidPointerType())
12304     return;
12305 
12306   if (TypeInfo.MustBeNull) {
12307     // Type tag with matching void type requires a null pointer.
12308     if (!ArgumentExpr->isNullPointerConstant(Context,
12309                                              Expr::NPC_ValueDependentIsNotNull)) {
12310       Diag(ArgumentExpr->getExprLoc(),
12311            diag::warn_type_safety_null_pointer_required)
12312           << ArgumentKind->getName()
12313           << ArgumentExpr->getSourceRange()
12314           << TypeTagExpr->getSourceRange();
12315     }
12316     return;
12317   }
12318 
12319   QualType RequiredType = TypeInfo.Type;
12320   if (IsPointerAttr)
12321     RequiredType = Context.getPointerType(RequiredType);
12322 
12323   bool mismatch = false;
12324   if (!TypeInfo.LayoutCompatible) {
12325     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12326 
12327     // C++11 [basic.fundamental] p1:
12328     // Plain char, signed char, and unsigned char are three distinct types.
12329     //
12330     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12331     // char' depending on the current char signedness mode.
12332     if (mismatch)
12333       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12334                                            RequiredType->getPointeeType())) ||
12335           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12336         mismatch = false;
12337   } else
12338     if (IsPointerAttr)
12339       mismatch = !isLayoutCompatible(Context,
12340                                      ArgumentType->getPointeeType(),
12341                                      RequiredType->getPointeeType());
12342     else
12343       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12344 
12345   if (mismatch)
12346     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12347         << ArgumentType << ArgumentKind
12348         << TypeInfo.LayoutCompatible << RequiredType
12349         << ArgumentExpr->getSourceRange()
12350         << TypeTagExpr->getSourceRange();
12351 }
12352 
12353 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12354                                          CharUnits Alignment) {
12355   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12356 }
12357 
12358 void Sema::DiagnoseMisalignedMembers() {
12359   for (MisalignedMember &m : MisalignedMembers) {
12360     const NamedDecl *ND = m.RD;
12361     if (ND->getName().empty()) {
12362       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12363         ND = TD;
12364     }
12365     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12366         << m.MD << ND << m.E->getSourceRange();
12367   }
12368   MisalignedMembers.clear();
12369 }
12370 
12371 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12372   E = E->IgnoreParens();
12373   if (!T->isPointerType() && !T->isIntegerType())
12374     return;
12375   if (isa<UnaryOperator>(E) &&
12376       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12377     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12378     if (isa<MemberExpr>(Op)) {
12379       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12380                           MisalignedMember(Op));
12381       if (MA != MisalignedMembers.end() &&
12382           (T->isIntegerType() ||
12383            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12384                                    Context.getTypeAlignInChars(
12385                                        T->getPointeeType()) <= MA->Alignment))))
12386         MisalignedMembers.erase(MA);
12387     }
12388   }
12389 }
12390 
12391 void Sema::RefersToMemberWithReducedAlignment(
12392     Expr *E,
12393     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12394         Action) {
12395   const auto *ME = dyn_cast<MemberExpr>(E);
12396   if (!ME)
12397     return;
12398 
12399   // No need to check expressions with an __unaligned-qualified type.
12400   if (E->getType().getQualifiers().hasUnaligned())
12401     return;
12402 
12403   // For a chain of MemberExpr like "a.b.c.d" this list
12404   // will keep FieldDecl's like [d, c, b].
12405   SmallVector<FieldDecl *, 4> ReverseMemberChain;
12406   const MemberExpr *TopME = nullptr;
12407   bool AnyIsPacked = false;
12408   do {
12409     QualType BaseType = ME->getBase()->getType();
12410     if (ME->isArrow())
12411       BaseType = BaseType->getPointeeType();
12412     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12413     if (RD->isInvalidDecl())
12414       return;
12415 
12416     ValueDecl *MD = ME->getMemberDecl();
12417     auto *FD = dyn_cast<FieldDecl>(MD);
12418     // We do not care about non-data members.
12419     if (!FD || FD->isInvalidDecl())
12420       return;
12421 
12422     AnyIsPacked =
12423         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12424     ReverseMemberChain.push_back(FD);
12425 
12426     TopME = ME;
12427     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12428   } while (ME);
12429   assert(TopME && "We did not compute a topmost MemberExpr!");
12430 
12431   // Not the scope of this diagnostic.
12432   if (!AnyIsPacked)
12433     return;
12434 
12435   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12436   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12437   // TODO: The innermost base of the member expression may be too complicated.
12438   // For now, just disregard these cases. This is left for future
12439   // improvement.
12440   if (!DRE && !isa<CXXThisExpr>(TopBase))
12441       return;
12442 
12443   // Alignment expected by the whole expression.
12444   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12445 
12446   // No need to do anything else with this case.
12447   if (ExpectedAlignment.isOne())
12448     return;
12449 
12450   // Synthesize offset of the whole access.
12451   CharUnits Offset;
12452   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12453        I++) {
12454     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12455   }
12456 
12457   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12458   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12459       ReverseMemberChain.back()->getParent()->getTypeForDecl());
12460 
12461   // The base expression of the innermost MemberExpr may give
12462   // stronger guarantees than the class containing the member.
12463   if (DRE && !TopME->isArrow()) {
12464     const ValueDecl *VD = DRE->getDecl();
12465     if (!VD->getType()->isReferenceType())
12466       CompleteObjectAlignment =
12467           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12468   }
12469 
12470   // Check if the synthesized offset fulfills the alignment.
12471   if (Offset % ExpectedAlignment != 0 ||
12472       // It may fulfill the offset it but the effective alignment may still be
12473       // lower than the expected expression alignment.
12474       CompleteObjectAlignment < ExpectedAlignment) {
12475     // If this happens, we want to determine a sensible culprit of this.
12476     // Intuitively, watching the chain of member expressions from right to
12477     // left, we start with the required alignment (as required by the field
12478     // type) but some packed attribute in that chain has reduced the alignment.
12479     // It may happen that another packed structure increases it again. But if
12480     // we are here such increase has not been enough. So pointing the first
12481     // FieldDecl that either is packed or else its RecordDecl is,
12482     // seems reasonable.
12483     FieldDecl *FD = nullptr;
12484     CharUnits Alignment;
12485     for (FieldDecl *FDI : ReverseMemberChain) {
12486       if (FDI->hasAttr<PackedAttr>() ||
12487           FDI->getParent()->hasAttr<PackedAttr>()) {
12488         FD = FDI;
12489         Alignment = std::min(
12490             Context.getTypeAlignInChars(FD->getType()),
12491             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12492         break;
12493       }
12494     }
12495     assert(FD && "We did not find a packed FieldDecl!");
12496     Action(E, FD->getParent(), FD, Alignment);
12497   }
12498 }
12499 
12500 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12501   using namespace std::placeholders;
12502 
12503   RefersToMemberWithReducedAlignment(
12504       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12505                      _2, _3, _4));
12506 }
12507