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/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/TargetBuiltins.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallBitVector.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/Support/ConvertUTF.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <limits>
41 using namespace clang;
42 using namespace sema;
43 
44 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45                                                     unsigned ByteNo) const {
46   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
47                                Context.getTargetInfo());
48 }
49 
50 /// Checks that a call expression's argument count is the desired number.
51 /// This is useful when doing custom type-checking.  Returns true on error.
52 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53   unsigned argCount = call->getNumArgs();
54   if (argCount == desiredArgCount) return false;
55 
56   if (argCount < desiredArgCount)
57     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58         << 0 /*function call*/ << desiredArgCount << argCount
59         << call->getSourceRange();
60 
61   // Highlight all the excess arguments.
62   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63                     call->getArg(argCount - 1)->getLocEnd());
64 
65   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66     << 0 /*function call*/ << desiredArgCount << argCount
67     << call->getArg(1)->getSourceRange();
68 }
69 
70 /// Check that the first argument to __builtin_annotation is an integer
71 /// and the second argument is a non-wide string literal.
72 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73   if (checkArgCount(S, TheCall, 2))
74     return true;
75 
76   // First argument should be an integer.
77   Expr *ValArg = TheCall->getArg(0);
78   QualType Ty = ValArg->getType();
79   if (!Ty->isIntegerType()) {
80     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81       << ValArg->getSourceRange();
82     return true;
83   }
84 
85   // Second argument should be a constant string.
86   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88   if (!Literal || !Literal->isAscii()) {
89     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90       << StrArg->getSourceRange();
91     return true;
92   }
93 
94   TheCall->setType(Ty);
95   return false;
96 }
97 
98 /// Check that the argument to __builtin_addressof is a glvalue, and set the
99 /// result type to the corresponding pointer type.
100 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101   if (checkArgCount(S, TheCall, 1))
102     return true;
103 
104   ExprResult Arg(TheCall->getArg(0));
105   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106   if (ResultType.isNull())
107     return true;
108 
109   TheCall->setArg(0, Arg.get());
110   TheCall->setType(ResultType);
111   return false;
112 }
113 
114 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
115 		                  CallExpr *TheCall, unsigned SizeIdx,
116                                   unsigned DstSizeIdx) {
117   if (TheCall->getNumArgs() <= SizeIdx ||
118       TheCall->getNumArgs() <= DstSizeIdx)
119     return;
120 
121   const Expr *SizeArg = TheCall->getArg(SizeIdx);
122   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
123 
124   llvm::APSInt Size, DstSize;
125 
126   // find out if both sizes are known at compile time
127   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
128       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
129     return;
130 
131   if (Size.ule(DstSize))
132     return;
133 
134   // confirmed overflow so generate the diagnostic.
135   IdentifierInfo *FnName = FDecl->getIdentifier();
136   SourceLocation SL = TheCall->getLocStart();
137   SourceRange SR = TheCall->getSourceRange();
138 
139   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
140 }
141 
142 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
143   if (checkArgCount(S, BuiltinCall, 2))
144     return true;
145 
146   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
147   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
148   Expr *Call = BuiltinCall->getArg(0);
149   Expr *Chain = BuiltinCall->getArg(1);
150 
151   if (Call->getStmtClass() != Stmt::CallExprClass) {
152     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153         << Call->getSourceRange();
154     return true;
155   }
156 
157   auto CE = cast<CallExpr>(Call);
158   if (CE->getCallee()->getType()->isBlockPointerType()) {
159     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160         << Call->getSourceRange();
161     return true;
162   }
163 
164   const Decl *TargetDecl = CE->getCalleeDecl();
165   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166     if (FD->getBuiltinID()) {
167       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168           << Call->getSourceRange();
169       return true;
170     }
171 
172   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174         << Call->getSourceRange();
175     return true;
176   }
177 
178   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
179   if (ChainResult.isInvalid())
180     return true;
181   if (!ChainResult.get()->getType()->isPointerType()) {
182     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183         << Chain->getSourceRange();
184     return true;
185   }
186 
187   QualType ReturnTy = CE->getCallReturnType();
188   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
189   QualType BuiltinTy = S.Context.getFunctionType(
190       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
191   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
192 
193   Builtin =
194       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
195 
196   BuiltinCall->setType(CE->getType());
197   BuiltinCall->setValueKind(CE->getValueKind());
198   BuiltinCall->setObjectKind(CE->getObjectKind());
199   BuiltinCall->setCallee(Builtin);
200   BuiltinCall->setArg(1, ChainResult.get());
201 
202   return false;
203 }
204 
205 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
206                                      Scope::ScopeFlags NeededScopeFlags,
207                                      unsigned DiagID) {
208   // Scopes aren't available during instantiation. Fortunately, builtin
209   // functions cannot be template args so they cannot be formed through template
210   // instantiation. Therefore checking once during the parse is sufficient.
211   if (!SemaRef.ActiveTemplateInstantiations.empty())
212     return false;
213 
214   Scope *S = SemaRef.getCurScope();
215   while (S && !S->isSEHExceptScope())
216     S = S->getParent();
217   if (!S || !(S->getFlags() & NeededScopeFlags)) {
218     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
219     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
220         << DRE->getDecl()->getIdentifier();
221     return true;
222   }
223 
224   return false;
225 }
226 
227 ExprResult
228 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
229                                CallExpr *TheCall) {
230   ExprResult TheCallResult(TheCall);
231 
232   // Find out if any arguments are required to be integer constant expressions.
233   unsigned ICEArguments = 0;
234   ASTContext::GetBuiltinTypeError Error;
235   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
236   if (Error != ASTContext::GE_None)
237     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
238 
239   // If any arguments are required to be ICE's, check and diagnose.
240   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
241     // Skip arguments not required to be ICE's.
242     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
243 
244     llvm::APSInt Result;
245     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
246       return true;
247     ICEArguments &= ~(1 << ArgNo);
248   }
249 
250   switch (BuiltinID) {
251   case Builtin::BI__builtin___CFStringMakeConstantString:
252     assert(TheCall->getNumArgs() == 1 &&
253            "Wrong # arguments to builtin CFStringMakeConstantString");
254     if (CheckObjCString(TheCall->getArg(0)))
255       return ExprError();
256     break;
257   case Builtin::BI__builtin_stdarg_start:
258   case Builtin::BI__builtin_va_start:
259     if (SemaBuiltinVAStart(TheCall))
260       return ExprError();
261     break;
262   case Builtin::BI__va_start: {
263     switch (Context.getTargetInfo().getTriple().getArch()) {
264     case llvm::Triple::arm:
265     case llvm::Triple::thumb:
266       if (SemaBuiltinVAStartARM(TheCall))
267         return ExprError();
268       break;
269     default:
270       if (SemaBuiltinVAStart(TheCall))
271         return ExprError();
272       break;
273     }
274     break;
275   }
276   case Builtin::BI__builtin_isgreater:
277   case Builtin::BI__builtin_isgreaterequal:
278   case Builtin::BI__builtin_isless:
279   case Builtin::BI__builtin_islessequal:
280   case Builtin::BI__builtin_islessgreater:
281   case Builtin::BI__builtin_isunordered:
282     if (SemaBuiltinUnorderedCompare(TheCall))
283       return ExprError();
284     break;
285   case Builtin::BI__builtin_fpclassify:
286     if (SemaBuiltinFPClassification(TheCall, 6))
287       return ExprError();
288     break;
289   case Builtin::BI__builtin_isfinite:
290   case Builtin::BI__builtin_isinf:
291   case Builtin::BI__builtin_isinf_sign:
292   case Builtin::BI__builtin_isnan:
293   case Builtin::BI__builtin_isnormal:
294     if (SemaBuiltinFPClassification(TheCall, 1))
295       return ExprError();
296     break;
297   case Builtin::BI__builtin_shufflevector:
298     return SemaBuiltinShuffleVector(TheCall);
299     // TheCall will be freed by the smart pointer here, but that's fine, since
300     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
301   case Builtin::BI__builtin_prefetch:
302     if (SemaBuiltinPrefetch(TheCall))
303       return ExprError();
304     break;
305   case Builtin::BI__assume:
306   case Builtin::BI__builtin_assume:
307     if (SemaBuiltinAssume(TheCall))
308       return ExprError();
309     break;
310   case Builtin::BI__builtin_assume_aligned:
311     if (SemaBuiltinAssumeAligned(TheCall))
312       return ExprError();
313     break;
314   case Builtin::BI__builtin_object_size:
315     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
316       return ExprError();
317     break;
318   case Builtin::BI__builtin_longjmp:
319     if (SemaBuiltinLongjmp(TheCall))
320       return ExprError();
321     break;
322 
323   case Builtin::BI__builtin_classify_type:
324     if (checkArgCount(*this, TheCall, 1)) return true;
325     TheCall->setType(Context.IntTy);
326     break;
327   case Builtin::BI__builtin_constant_p:
328     if (checkArgCount(*this, TheCall, 1)) return true;
329     TheCall->setType(Context.IntTy);
330     break;
331   case Builtin::BI__sync_fetch_and_add:
332   case Builtin::BI__sync_fetch_and_add_1:
333   case Builtin::BI__sync_fetch_and_add_2:
334   case Builtin::BI__sync_fetch_and_add_4:
335   case Builtin::BI__sync_fetch_and_add_8:
336   case Builtin::BI__sync_fetch_and_add_16:
337   case Builtin::BI__sync_fetch_and_sub:
338   case Builtin::BI__sync_fetch_and_sub_1:
339   case Builtin::BI__sync_fetch_and_sub_2:
340   case Builtin::BI__sync_fetch_and_sub_4:
341   case Builtin::BI__sync_fetch_and_sub_8:
342   case Builtin::BI__sync_fetch_and_sub_16:
343   case Builtin::BI__sync_fetch_and_or:
344   case Builtin::BI__sync_fetch_and_or_1:
345   case Builtin::BI__sync_fetch_and_or_2:
346   case Builtin::BI__sync_fetch_and_or_4:
347   case Builtin::BI__sync_fetch_and_or_8:
348   case Builtin::BI__sync_fetch_and_or_16:
349   case Builtin::BI__sync_fetch_and_and:
350   case Builtin::BI__sync_fetch_and_and_1:
351   case Builtin::BI__sync_fetch_and_and_2:
352   case Builtin::BI__sync_fetch_and_and_4:
353   case Builtin::BI__sync_fetch_and_and_8:
354   case Builtin::BI__sync_fetch_and_and_16:
355   case Builtin::BI__sync_fetch_and_xor:
356   case Builtin::BI__sync_fetch_and_xor_1:
357   case Builtin::BI__sync_fetch_and_xor_2:
358   case Builtin::BI__sync_fetch_and_xor_4:
359   case Builtin::BI__sync_fetch_and_xor_8:
360   case Builtin::BI__sync_fetch_and_xor_16:
361   case Builtin::BI__sync_fetch_and_nand:
362   case Builtin::BI__sync_fetch_and_nand_1:
363   case Builtin::BI__sync_fetch_and_nand_2:
364   case Builtin::BI__sync_fetch_and_nand_4:
365   case Builtin::BI__sync_fetch_and_nand_8:
366   case Builtin::BI__sync_fetch_and_nand_16:
367   case Builtin::BI__sync_add_and_fetch:
368   case Builtin::BI__sync_add_and_fetch_1:
369   case Builtin::BI__sync_add_and_fetch_2:
370   case Builtin::BI__sync_add_and_fetch_4:
371   case Builtin::BI__sync_add_and_fetch_8:
372   case Builtin::BI__sync_add_and_fetch_16:
373   case Builtin::BI__sync_sub_and_fetch:
374   case Builtin::BI__sync_sub_and_fetch_1:
375   case Builtin::BI__sync_sub_and_fetch_2:
376   case Builtin::BI__sync_sub_and_fetch_4:
377   case Builtin::BI__sync_sub_and_fetch_8:
378   case Builtin::BI__sync_sub_and_fetch_16:
379   case Builtin::BI__sync_and_and_fetch:
380   case Builtin::BI__sync_and_and_fetch_1:
381   case Builtin::BI__sync_and_and_fetch_2:
382   case Builtin::BI__sync_and_and_fetch_4:
383   case Builtin::BI__sync_and_and_fetch_8:
384   case Builtin::BI__sync_and_and_fetch_16:
385   case Builtin::BI__sync_or_and_fetch:
386   case Builtin::BI__sync_or_and_fetch_1:
387   case Builtin::BI__sync_or_and_fetch_2:
388   case Builtin::BI__sync_or_and_fetch_4:
389   case Builtin::BI__sync_or_and_fetch_8:
390   case Builtin::BI__sync_or_and_fetch_16:
391   case Builtin::BI__sync_xor_and_fetch:
392   case Builtin::BI__sync_xor_and_fetch_1:
393   case Builtin::BI__sync_xor_and_fetch_2:
394   case Builtin::BI__sync_xor_and_fetch_4:
395   case Builtin::BI__sync_xor_and_fetch_8:
396   case Builtin::BI__sync_xor_and_fetch_16:
397   case Builtin::BI__sync_nand_and_fetch:
398   case Builtin::BI__sync_nand_and_fetch_1:
399   case Builtin::BI__sync_nand_and_fetch_2:
400   case Builtin::BI__sync_nand_and_fetch_4:
401   case Builtin::BI__sync_nand_and_fetch_8:
402   case Builtin::BI__sync_nand_and_fetch_16:
403   case Builtin::BI__sync_val_compare_and_swap:
404   case Builtin::BI__sync_val_compare_and_swap_1:
405   case Builtin::BI__sync_val_compare_and_swap_2:
406   case Builtin::BI__sync_val_compare_and_swap_4:
407   case Builtin::BI__sync_val_compare_and_swap_8:
408   case Builtin::BI__sync_val_compare_and_swap_16:
409   case Builtin::BI__sync_bool_compare_and_swap:
410   case Builtin::BI__sync_bool_compare_and_swap_1:
411   case Builtin::BI__sync_bool_compare_and_swap_2:
412   case Builtin::BI__sync_bool_compare_and_swap_4:
413   case Builtin::BI__sync_bool_compare_and_swap_8:
414   case Builtin::BI__sync_bool_compare_and_swap_16:
415   case Builtin::BI__sync_lock_test_and_set:
416   case Builtin::BI__sync_lock_test_and_set_1:
417   case Builtin::BI__sync_lock_test_and_set_2:
418   case Builtin::BI__sync_lock_test_and_set_4:
419   case Builtin::BI__sync_lock_test_and_set_8:
420   case Builtin::BI__sync_lock_test_and_set_16:
421   case Builtin::BI__sync_lock_release:
422   case Builtin::BI__sync_lock_release_1:
423   case Builtin::BI__sync_lock_release_2:
424   case Builtin::BI__sync_lock_release_4:
425   case Builtin::BI__sync_lock_release_8:
426   case Builtin::BI__sync_lock_release_16:
427   case Builtin::BI__sync_swap:
428   case Builtin::BI__sync_swap_1:
429   case Builtin::BI__sync_swap_2:
430   case Builtin::BI__sync_swap_4:
431   case Builtin::BI__sync_swap_8:
432   case Builtin::BI__sync_swap_16:
433     return SemaBuiltinAtomicOverloaded(TheCallResult);
434 #define BUILTIN(ID, TYPE, ATTRS)
435 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
436   case Builtin::BI##ID: \
437     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
438 #include "clang/Basic/Builtins.def"
439   case Builtin::BI__builtin_annotation:
440     if (SemaBuiltinAnnotation(*this, TheCall))
441       return ExprError();
442     break;
443   case Builtin::BI__builtin_addressof:
444     if (SemaBuiltinAddressof(*this, TheCall))
445       return ExprError();
446     break;
447   case Builtin::BI__builtin_operator_new:
448   case Builtin::BI__builtin_operator_delete:
449     if (!getLangOpts().CPlusPlus) {
450       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
451         << (BuiltinID == Builtin::BI__builtin_operator_new
452                 ? "__builtin_operator_new"
453                 : "__builtin_operator_delete")
454         << "C++";
455       return ExprError();
456     }
457     // CodeGen assumes it can find the global new and delete to call,
458     // so ensure that they are declared.
459     DeclareGlobalNewDelete();
460     break;
461 
462   // check secure string manipulation functions where overflows
463   // are detectable at compile time
464   case Builtin::BI__builtin___memcpy_chk:
465   case Builtin::BI__builtin___memmove_chk:
466   case Builtin::BI__builtin___memset_chk:
467   case Builtin::BI__builtin___strlcat_chk:
468   case Builtin::BI__builtin___strlcpy_chk:
469   case Builtin::BI__builtin___strncat_chk:
470   case Builtin::BI__builtin___strncpy_chk:
471   case Builtin::BI__builtin___stpncpy_chk:
472     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
473     break;
474   case Builtin::BI__builtin___memccpy_chk:
475     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
476     break;
477   case Builtin::BI__builtin___snprintf_chk:
478   case Builtin::BI__builtin___vsnprintf_chk:
479     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
480     break;
481 
482   case Builtin::BI__builtin_call_with_static_chain:
483     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
484       return ExprError();
485     break;
486 
487   case Builtin::BI__exception_code:
488   case Builtin::BI_exception_code: {
489     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
490                                  diag::err_seh___except_block))
491       return ExprError();
492     break;
493   }
494   case Builtin::BI__exception_info:
495   case Builtin::BI_exception_info: {
496     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
497                                  diag::err_seh___except_filter))
498       return ExprError();
499     break;
500   }
501 
502   }
503 
504   // Since the target specific builtins for each arch overlap, only check those
505   // of the arch we are compiling for.
506   if (BuiltinID >= Builtin::FirstTSBuiltin) {
507     switch (Context.getTargetInfo().getTriple().getArch()) {
508       case llvm::Triple::arm:
509       case llvm::Triple::armeb:
510       case llvm::Triple::thumb:
511       case llvm::Triple::thumbeb:
512         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
513           return ExprError();
514         break;
515       case llvm::Triple::aarch64:
516       case llvm::Triple::aarch64_be:
517         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
518           return ExprError();
519         break;
520       case llvm::Triple::mips:
521       case llvm::Triple::mipsel:
522       case llvm::Triple::mips64:
523       case llvm::Triple::mips64el:
524         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
525           return ExprError();
526         break;
527       case llvm::Triple::x86:
528       case llvm::Triple::x86_64:
529         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
530           return ExprError();
531         break;
532       default:
533         break;
534     }
535   }
536 
537   return TheCallResult;
538 }
539 
540 // Get the valid immediate range for the specified NEON type code.
541 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
542   NeonTypeFlags Type(t);
543   int IsQuad = ForceQuad ? true : Type.isQuad();
544   switch (Type.getEltType()) {
545   case NeonTypeFlags::Int8:
546   case NeonTypeFlags::Poly8:
547     return shift ? 7 : (8 << IsQuad) - 1;
548   case NeonTypeFlags::Int16:
549   case NeonTypeFlags::Poly16:
550     return shift ? 15 : (4 << IsQuad) - 1;
551   case NeonTypeFlags::Int32:
552     return shift ? 31 : (2 << IsQuad) - 1;
553   case NeonTypeFlags::Int64:
554   case NeonTypeFlags::Poly64:
555     return shift ? 63 : (1 << IsQuad) - 1;
556   case NeonTypeFlags::Poly128:
557     return shift ? 127 : (1 << IsQuad) - 1;
558   case NeonTypeFlags::Float16:
559     assert(!shift && "cannot shift float types!");
560     return (4 << IsQuad) - 1;
561   case NeonTypeFlags::Float32:
562     assert(!shift && "cannot shift float types!");
563     return (2 << IsQuad) - 1;
564   case NeonTypeFlags::Float64:
565     assert(!shift && "cannot shift float types!");
566     return (1 << IsQuad) - 1;
567   }
568   llvm_unreachable("Invalid NeonTypeFlag!");
569 }
570 
571 /// getNeonEltType - Return the QualType corresponding to the elements of
572 /// the vector type specified by the NeonTypeFlags.  This is used to check
573 /// the pointer arguments for Neon load/store intrinsics.
574 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
575                                bool IsPolyUnsigned, bool IsInt64Long) {
576   switch (Flags.getEltType()) {
577   case NeonTypeFlags::Int8:
578     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
579   case NeonTypeFlags::Int16:
580     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
581   case NeonTypeFlags::Int32:
582     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
583   case NeonTypeFlags::Int64:
584     if (IsInt64Long)
585       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
586     else
587       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
588                                 : Context.LongLongTy;
589   case NeonTypeFlags::Poly8:
590     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
591   case NeonTypeFlags::Poly16:
592     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
593   case NeonTypeFlags::Poly64:
594     return Context.UnsignedLongTy;
595   case NeonTypeFlags::Poly128:
596     break;
597   case NeonTypeFlags::Float16:
598     return Context.HalfTy;
599   case NeonTypeFlags::Float32:
600     return Context.FloatTy;
601   case NeonTypeFlags::Float64:
602     return Context.DoubleTy;
603   }
604   llvm_unreachable("Invalid NeonTypeFlag!");
605 }
606 
607 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
608   llvm::APSInt Result;
609   uint64_t mask = 0;
610   unsigned TV = 0;
611   int PtrArgNum = -1;
612   bool HasConstPtr = false;
613   switch (BuiltinID) {
614 #define GET_NEON_OVERLOAD_CHECK
615 #include "clang/Basic/arm_neon.inc"
616 #undef GET_NEON_OVERLOAD_CHECK
617   }
618 
619   // For NEON intrinsics which are overloaded on vector element type, validate
620   // the immediate which specifies which variant to emit.
621   unsigned ImmArg = TheCall->getNumArgs()-1;
622   if (mask) {
623     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
624       return true;
625 
626     TV = Result.getLimitedValue(64);
627     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
628       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
629         << TheCall->getArg(ImmArg)->getSourceRange();
630   }
631 
632   if (PtrArgNum >= 0) {
633     // Check that pointer arguments have the specified type.
634     Expr *Arg = TheCall->getArg(PtrArgNum);
635     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
636       Arg = ICE->getSubExpr();
637     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
638     QualType RHSTy = RHS.get()->getType();
639 
640     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
641     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
642     bool IsInt64Long =
643         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
644     QualType EltTy =
645         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
646     if (HasConstPtr)
647       EltTy = EltTy.withConst();
648     QualType LHSTy = Context.getPointerType(EltTy);
649     AssignConvertType ConvTy;
650     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
651     if (RHS.isInvalid())
652       return true;
653     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
654                                  RHS.get(), AA_Assigning))
655       return true;
656   }
657 
658   // For NEON intrinsics which take an immediate value as part of the
659   // instruction, range check them here.
660   unsigned i = 0, l = 0, u = 0;
661   switch (BuiltinID) {
662   default:
663     return false;
664 #define GET_NEON_IMMEDIATE_CHECK
665 #include "clang/Basic/arm_neon.inc"
666 #undef GET_NEON_IMMEDIATE_CHECK
667   }
668 
669   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
670 }
671 
672 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
673                                         unsigned MaxWidth) {
674   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
675           BuiltinID == ARM::BI__builtin_arm_ldaex ||
676           BuiltinID == ARM::BI__builtin_arm_strex ||
677           BuiltinID == ARM::BI__builtin_arm_stlex ||
678           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
679           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
680           BuiltinID == AArch64::BI__builtin_arm_strex ||
681           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
682          "unexpected ARM builtin");
683   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
684                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
685                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
686                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
687 
688   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
689 
690   // Ensure that we have the proper number of arguments.
691   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
692     return true;
693 
694   // Inspect the pointer argument of the atomic builtin.  This should always be
695   // a pointer type, whose element is an integral scalar or pointer type.
696   // Because it is a pointer type, we don't have to worry about any implicit
697   // casts here.
698   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
699   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
700   if (PointerArgRes.isInvalid())
701     return true;
702   PointerArg = PointerArgRes.get();
703 
704   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
705   if (!pointerType) {
706     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
707       << PointerArg->getType() << PointerArg->getSourceRange();
708     return true;
709   }
710 
711   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
712   // task is to insert the appropriate casts into the AST. First work out just
713   // what the appropriate type is.
714   QualType ValType = pointerType->getPointeeType();
715   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
716   if (IsLdrex)
717     AddrType.addConst();
718 
719   // Issue a warning if the cast is dodgy.
720   CastKind CastNeeded = CK_NoOp;
721   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
722     CastNeeded = CK_BitCast;
723     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
724       << PointerArg->getType()
725       << Context.getPointerType(AddrType)
726       << AA_Passing << PointerArg->getSourceRange();
727   }
728 
729   // Finally, do the cast and replace the argument with the corrected version.
730   AddrType = Context.getPointerType(AddrType);
731   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
732   if (PointerArgRes.isInvalid())
733     return true;
734   PointerArg = PointerArgRes.get();
735 
736   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
737 
738   // In general, we allow ints, floats and pointers to be loaded and stored.
739   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
740       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
741     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
742       << PointerArg->getType() << PointerArg->getSourceRange();
743     return true;
744   }
745 
746   // But ARM doesn't have instructions to deal with 128-bit versions.
747   if (Context.getTypeSize(ValType) > MaxWidth) {
748     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
749     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
750       << PointerArg->getType() << PointerArg->getSourceRange();
751     return true;
752   }
753 
754   switch (ValType.getObjCLifetime()) {
755   case Qualifiers::OCL_None:
756   case Qualifiers::OCL_ExplicitNone:
757     // okay
758     break;
759 
760   case Qualifiers::OCL_Weak:
761   case Qualifiers::OCL_Strong:
762   case Qualifiers::OCL_Autoreleasing:
763     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
764       << ValType << PointerArg->getSourceRange();
765     return true;
766   }
767 
768 
769   if (IsLdrex) {
770     TheCall->setType(ValType);
771     return false;
772   }
773 
774   // Initialize the argument to be stored.
775   ExprResult ValArg = TheCall->getArg(0);
776   InitializedEntity Entity = InitializedEntity::InitializeParameter(
777       Context, ValType, /*consume*/ false);
778   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
779   if (ValArg.isInvalid())
780     return true;
781   TheCall->setArg(0, ValArg.get());
782 
783   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
784   // but the custom checker bypasses all default analysis.
785   TheCall->setType(Context.IntTy);
786   return false;
787 }
788 
789 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
790   llvm::APSInt Result;
791 
792   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
793       BuiltinID == ARM::BI__builtin_arm_ldaex ||
794       BuiltinID == ARM::BI__builtin_arm_strex ||
795       BuiltinID == ARM::BI__builtin_arm_stlex) {
796     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
797   }
798 
799   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
800     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
801       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
802   }
803 
804   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
805     return true;
806 
807   // For intrinsics which take an immediate value as part of the instruction,
808   // range check them here.
809   unsigned i = 0, l = 0, u = 0;
810   switch (BuiltinID) {
811   default: return false;
812   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
813   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
814   case ARM::BI__builtin_arm_vcvtr_f:
815   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
816   case ARM::BI__builtin_arm_dmb:
817   case ARM::BI__builtin_arm_dsb:
818   case ARM::BI__builtin_arm_isb:
819   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
820   }
821 
822   // FIXME: VFP Intrinsics should error if VFP not present.
823   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
824 }
825 
826 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
827                                          CallExpr *TheCall) {
828   llvm::APSInt Result;
829 
830   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
831       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
832       BuiltinID == AArch64::BI__builtin_arm_strex ||
833       BuiltinID == AArch64::BI__builtin_arm_stlex) {
834     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
835   }
836 
837   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
838     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
839       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
840       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
841       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
842   }
843 
844   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
845     return true;
846 
847   // For intrinsics which take an immediate value as part of the instruction,
848   // range check them here.
849   unsigned i = 0, l = 0, u = 0;
850   switch (BuiltinID) {
851   default: return false;
852   case AArch64::BI__builtin_arm_dmb:
853   case AArch64::BI__builtin_arm_dsb:
854   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
855   }
856 
857   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
858 }
859 
860 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
861   unsigned i = 0, l = 0, u = 0;
862   switch (BuiltinID) {
863   default: return false;
864   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
865   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
866   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
867   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
868   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
869   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
870   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
871   }
872 
873   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
874 }
875 
876 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
877   unsigned i = 0, l = 0, u = 0;
878   switch (BuiltinID) {
879   default: return false;
880   case X86::BI_mm_prefetch: i = 1; l = 0; u = 3; break;
881   case X86::BI__builtin_ia32_vextractf128_pd256:
882   case X86::BI__builtin_ia32_vextractf128_ps256:
883   case X86::BI__builtin_ia32_vextractf128_si256:
884   case X86::BI__builtin_ia32_extract128i256: i = 1, l = 0, u = 1; break;
885   case X86::BI__builtin_ia32_vinsertf128_pd256:
886   case X86::BI__builtin_ia32_vinsertf128_ps256:
887   case X86::BI__builtin_ia32_vinsertf128_si256:
888   case X86::BI__builtin_ia32_insert128i256:
889   case X86::BI__builtin_ia32_blendpd: i = 2, l = 0; u = 1; break;
890   case X86::BI__builtin_ia32_blendps:
891   case X86::BI__builtin_ia32_blendpd256:
892   case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3; break;
893   case X86::BI__builtin_ia32_vpermil2pd:
894   case X86::BI__builtin_ia32_vpermil2pd256:
895   case X86::BI__builtin_ia32_vpermil2ps:
896   case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3; break;
897   case X86::BI__builtin_ia32_cmpb128_mask:
898   case X86::BI__builtin_ia32_cmpw128_mask:
899   case X86::BI__builtin_ia32_cmpd128_mask:
900   case X86::BI__builtin_ia32_cmpq128_mask:
901   case X86::BI__builtin_ia32_cmpb256_mask:
902   case X86::BI__builtin_ia32_cmpw256_mask:
903   case X86::BI__builtin_ia32_cmpd256_mask:
904   case X86::BI__builtin_ia32_cmpq256_mask:
905   case X86::BI__builtin_ia32_cmpb512_mask:
906   case X86::BI__builtin_ia32_cmpw512_mask:
907   case X86::BI__builtin_ia32_cmpd512_mask:
908   case X86::BI__builtin_ia32_cmpq512_mask:
909   case X86::BI__builtin_ia32_ucmpb128_mask:
910   case X86::BI__builtin_ia32_ucmpw128_mask:
911   case X86::BI__builtin_ia32_ucmpd128_mask:
912   case X86::BI__builtin_ia32_ucmpq128_mask:
913   case X86::BI__builtin_ia32_ucmpb256_mask:
914   case X86::BI__builtin_ia32_ucmpw256_mask:
915   case X86::BI__builtin_ia32_ucmpd256_mask:
916   case X86::BI__builtin_ia32_ucmpq256_mask:
917   case X86::BI__builtin_ia32_ucmpb512_mask:
918   case X86::BI__builtin_ia32_ucmpw512_mask:
919   case X86::BI__builtin_ia32_ucmpd512_mask:
920   case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7; break;
921   case X86::BI__builtin_ia32_roundps:
922   case X86::BI__builtin_ia32_roundpd:
923   case X86::BI__builtin_ia32_roundps256:
924   case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15; break;
925   case X86::BI__builtin_ia32_roundss:
926   case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15; break;
927   case X86::BI__builtin_ia32_cmpps:
928   case X86::BI__builtin_ia32_cmpss:
929   case X86::BI__builtin_ia32_cmppd:
930   case X86::BI__builtin_ia32_cmpsd:
931   case X86::BI__builtin_ia32_cmpps256:
932   case X86::BI__builtin_ia32_cmppd256:
933   case X86::BI__builtin_ia32_cmpps512_mask:
934   case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31; break;
935   case X86::BI__builtin_ia32_vpcomub:
936   case X86::BI__builtin_ia32_vpcomuw:
937   case X86::BI__builtin_ia32_vpcomud:
938   case X86::BI__builtin_ia32_vpcomuq:
939   case X86::BI__builtin_ia32_vpcomb:
940   case X86::BI__builtin_ia32_vpcomw:
941   case X86::BI__builtin_ia32_vpcomd:
942   case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7; break;
943   }
944   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
945 }
946 
947 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
948 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
949 /// Returns true when the format fits the function and the FormatStringInfo has
950 /// been populated.
951 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
952                                FormatStringInfo *FSI) {
953   FSI->HasVAListArg = Format->getFirstArg() == 0;
954   FSI->FormatIdx = Format->getFormatIdx() - 1;
955   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
956 
957   // The way the format attribute works in GCC, the implicit this argument
958   // of member functions is counted. However, it doesn't appear in our own
959   // lists, so decrement format_idx in that case.
960   if (IsCXXMember) {
961     if(FSI->FormatIdx == 0)
962       return false;
963     --FSI->FormatIdx;
964     if (FSI->FirstDataArg != 0)
965       --FSI->FirstDataArg;
966   }
967   return true;
968 }
969 
970 /// Checks if a the given expression evaluates to null.
971 ///
972 /// \brief Returns true if the value evaluates to null.
973 static bool CheckNonNullExpr(Sema &S,
974                              const Expr *Expr) {
975   // As a special case, transparent unions initialized with zero are
976   // considered null for the purposes of the nonnull attribute.
977   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
978     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
979       if (const CompoundLiteralExpr *CLE =
980           dyn_cast<CompoundLiteralExpr>(Expr))
981         if (const InitListExpr *ILE =
982             dyn_cast<InitListExpr>(CLE->getInitializer()))
983           Expr = ILE->getInit(0);
984   }
985 
986   bool Result;
987   return (!Expr->isValueDependent() &&
988           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
989           !Result);
990 }
991 
992 static void CheckNonNullArgument(Sema &S,
993                                  const Expr *ArgExpr,
994                                  SourceLocation CallSiteLoc) {
995   if (CheckNonNullExpr(S, ArgExpr))
996     S.Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
997 }
998 
999 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1000   FormatStringInfo FSI;
1001   if ((GetFormatStringType(Format) == FST_NSString) &&
1002       getFormatStringInfo(Format, false, &FSI)) {
1003     Idx = FSI.FormatIdx;
1004     return true;
1005   }
1006   return false;
1007 }
1008 /// \brief Diagnose use of %s directive in an NSString which is being passed
1009 /// as formatting string to formatting method.
1010 static void
1011 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1012                                         const NamedDecl *FDecl,
1013                                         Expr **Args,
1014                                         unsigned NumArgs) {
1015   unsigned Idx = 0;
1016   bool Format = false;
1017   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1018   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
1019     Idx = 2;
1020     Format = true;
1021   }
1022   else
1023     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1024       if (S.GetFormatNSStringIdx(I, Idx)) {
1025         Format = true;
1026         break;
1027       }
1028     }
1029   if (!Format || NumArgs <= Idx)
1030     return;
1031   const Expr *FormatExpr = Args[Idx];
1032   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1033     FormatExpr = CSCE->getSubExpr();
1034   const StringLiteral *FormatString;
1035   if (const ObjCStringLiteral *OSL =
1036       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1037     FormatString = OSL->getString();
1038   else
1039     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1040   if (!FormatString)
1041     return;
1042   if (S.FormatStringHasSArg(FormatString)) {
1043     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1044       << "%s" << 1 << 1;
1045     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1046       << FDecl->getDeclName();
1047   }
1048 }
1049 
1050 static void CheckNonNullArguments(Sema &S,
1051                                   const NamedDecl *FDecl,
1052                                   ArrayRef<const Expr *> Args,
1053                                   SourceLocation CallSiteLoc) {
1054   // Check the attributes attached to the method/function itself.
1055   llvm::SmallBitVector NonNullArgs;
1056   for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1057     if (!NonNull->args_size()) {
1058       // Easy case: all pointer arguments are nonnull.
1059       for (const auto *Arg : Args)
1060         if (S.isValidPointerAttrType(Arg->getType()))
1061           CheckNonNullArgument(S, Arg, CallSiteLoc);
1062       return;
1063     }
1064 
1065     for (unsigned Val : NonNull->args()) {
1066       if (Val >= Args.size())
1067         continue;
1068       if (NonNullArgs.empty())
1069         NonNullArgs.resize(Args.size());
1070       NonNullArgs.set(Val);
1071     }
1072   }
1073 
1074   // Check the attributes on the parameters.
1075   ArrayRef<ParmVarDecl*> parms;
1076   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1077     parms = FD->parameters();
1078   else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(FDecl))
1079     parms = MD->parameters();
1080 
1081   unsigned ArgIndex = 0;
1082   for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1083        I != E; ++I, ++ArgIndex) {
1084     const ParmVarDecl *PVD = *I;
1085     if (PVD->hasAttr<NonNullAttr>() ||
1086         (ArgIndex < NonNullArgs.size() && NonNullArgs[ArgIndex]))
1087       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
1088   }
1089 
1090   // In case this is a variadic call, check any remaining arguments.
1091   for (/**/; ArgIndex < NonNullArgs.size(); ++ArgIndex)
1092     if (NonNullArgs[ArgIndex])
1093       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
1094 }
1095 
1096 /// Handles the checks for format strings, non-POD arguments to vararg
1097 /// functions, and NULL arguments passed to non-NULL parameters.
1098 void Sema::checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args,
1099                      unsigned NumParams, bool IsMemberFunction,
1100                      SourceLocation Loc, SourceRange Range,
1101                      VariadicCallType CallType) {
1102   // FIXME: We should check as much as we can in the template definition.
1103   if (CurContext->isDependentContext())
1104     return;
1105 
1106   // Printf and scanf checking.
1107   llvm::SmallBitVector CheckedVarArgs;
1108   if (FDecl) {
1109     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1110       // Only create vector if there are format attributes.
1111       CheckedVarArgs.resize(Args.size());
1112 
1113       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
1114                            CheckedVarArgs);
1115     }
1116   }
1117 
1118   // Refuse POD arguments that weren't caught by the format string
1119   // checks above.
1120   if (CallType != VariadicDoesNotApply) {
1121     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
1122       // Args[ArgIdx] can be null in malformed code.
1123       if (const Expr *Arg = Args[ArgIdx]) {
1124         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1125           checkVariadicArgument(Arg, CallType);
1126       }
1127     }
1128   }
1129 
1130   if (FDecl) {
1131     CheckNonNullArguments(*this, FDecl, Args, Loc);
1132 
1133     // Type safety checking.
1134     for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1135       CheckArgumentWithTypeTag(I, Args.data());
1136   }
1137 }
1138 
1139 /// CheckConstructorCall - Check a constructor call for correctness and safety
1140 /// properties not enforced by the C type system.
1141 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1142                                 ArrayRef<const Expr *> Args,
1143                                 const FunctionProtoType *Proto,
1144                                 SourceLocation Loc) {
1145   VariadicCallType CallType =
1146     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
1147   checkCall(FDecl, Args, Proto->getNumParams(),
1148             /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
1149 }
1150 
1151 /// CheckFunctionCall - Check a direct function call for various correctness
1152 /// and safety properties not strictly enforced by the C type system.
1153 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1154                              const FunctionProtoType *Proto) {
1155   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1156                               isa<CXXMethodDecl>(FDecl);
1157   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1158                           IsMemberOperatorCall;
1159   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1160                                                   TheCall->getCallee());
1161   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1162   Expr** Args = TheCall->getArgs();
1163   unsigned NumArgs = TheCall->getNumArgs();
1164   if (IsMemberOperatorCall) {
1165     // If this is a call to a member operator, hide the first argument
1166     // from checkCall.
1167     // FIXME: Our choice of AST representation here is less than ideal.
1168     ++Args;
1169     --NumArgs;
1170   }
1171   checkCall(FDecl, llvm::makeArrayRef(Args, NumArgs), NumParams,
1172             IsMemberFunction, TheCall->getRParenLoc(),
1173             TheCall->getCallee()->getSourceRange(), CallType);
1174 
1175   IdentifierInfo *FnInfo = FDecl->getIdentifier();
1176   // None of the checks below are needed for functions that don't have
1177   // simple names (e.g., C++ conversion functions).
1178   if (!FnInfo)
1179     return false;
1180 
1181   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
1182   if (getLangOpts().ObjC1)
1183     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
1184 
1185   unsigned CMId = FDecl->getMemoryFunctionKind();
1186   if (CMId == 0)
1187     return false;
1188 
1189   // Handle memory setting and copying functions.
1190   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
1191     CheckStrlcpycatArguments(TheCall, FnInfo);
1192   else if (CMId == Builtin::BIstrncat)
1193     CheckStrncatArguments(TheCall, FnInfo);
1194   else
1195     CheckMemaccessArguments(TheCall, CMId, FnInfo);
1196 
1197   return false;
1198 }
1199 
1200 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
1201                                ArrayRef<const Expr *> Args) {
1202   VariadicCallType CallType =
1203       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
1204 
1205   checkCall(Method, Args, Method->param_size(),
1206             /*IsMemberFunction=*/false,
1207             lbrac, Method->getSourceRange(), CallType);
1208 
1209   return false;
1210 }
1211 
1212 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1213                             const FunctionProtoType *Proto) {
1214   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
1215   if (!V)
1216     return false;
1217 
1218   QualType Ty = V->getType();
1219   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
1220     return false;
1221 
1222   VariadicCallType CallType;
1223   if (!Proto || !Proto->isVariadic()) {
1224     CallType = VariadicDoesNotApply;
1225   } else if (Ty->isBlockPointerType()) {
1226     CallType = VariadicBlock;
1227   } else { // Ty->isFunctionPointerType()
1228     CallType = VariadicFunction;
1229   }
1230   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1231 
1232   checkCall(NDecl, llvm::makeArrayRef(TheCall->getArgs(),
1233                                       TheCall->getNumArgs()),
1234             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1235             TheCall->getCallee()->getSourceRange(), CallType);
1236 
1237   return false;
1238 }
1239 
1240 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1241 /// such as function pointers returned from functions.
1242 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
1243   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
1244                                                   TheCall->getCallee());
1245   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
1246 
1247   checkCall(/*FDecl=*/nullptr,
1248             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1249             NumParams, /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1250             TheCall->getCallee()->getSourceRange(), CallType);
1251 
1252   return false;
1253 }
1254 
1255 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1256   if (Ordering < AtomicExpr::AO_ABI_memory_order_relaxed ||
1257       Ordering > AtomicExpr::AO_ABI_memory_order_seq_cst)
1258     return false;
1259 
1260   switch (Op) {
1261   case AtomicExpr::AO__c11_atomic_init:
1262     llvm_unreachable("There is no ordering argument for an init");
1263 
1264   case AtomicExpr::AO__c11_atomic_load:
1265   case AtomicExpr::AO__atomic_load_n:
1266   case AtomicExpr::AO__atomic_load:
1267     return Ordering != AtomicExpr::AO_ABI_memory_order_release &&
1268            Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1269 
1270   case AtomicExpr::AO__c11_atomic_store:
1271   case AtomicExpr::AO__atomic_store:
1272   case AtomicExpr::AO__atomic_store_n:
1273     return Ordering != AtomicExpr::AO_ABI_memory_order_consume &&
1274            Ordering != AtomicExpr::AO_ABI_memory_order_acquire &&
1275            Ordering != AtomicExpr::AO_ABI_memory_order_acq_rel;
1276 
1277   default:
1278     return true;
1279   }
1280 }
1281 
1282 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1283                                          AtomicExpr::AtomicOp Op) {
1284   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1285   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1286 
1287   // All these operations take one of the following forms:
1288   enum {
1289     // C    __c11_atomic_init(A *, C)
1290     Init,
1291     // C    __c11_atomic_load(A *, int)
1292     Load,
1293     // void __atomic_load(A *, CP, int)
1294     Copy,
1295     // C    __c11_atomic_add(A *, M, int)
1296     Arithmetic,
1297     // C    __atomic_exchange_n(A *, CP, int)
1298     Xchg,
1299     // void __atomic_exchange(A *, C *, CP, int)
1300     GNUXchg,
1301     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1302     C11CmpXchg,
1303     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1304     GNUCmpXchg
1305   } Form = Init;
1306   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1307   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1308   // where:
1309   //   C is an appropriate type,
1310   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1311   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1312   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1313   //   the int parameters are for orderings.
1314 
1315   assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1316          AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
1317          && "need to update code for modified C11 atomics");
1318   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1319                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1320   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1321              Op == AtomicExpr::AO__atomic_store_n ||
1322              Op == AtomicExpr::AO__atomic_exchange_n ||
1323              Op == AtomicExpr::AO__atomic_compare_exchange_n;
1324   bool IsAddSub = false;
1325 
1326   switch (Op) {
1327   case AtomicExpr::AO__c11_atomic_init:
1328     Form = Init;
1329     break;
1330 
1331   case AtomicExpr::AO__c11_atomic_load:
1332   case AtomicExpr::AO__atomic_load_n:
1333     Form = Load;
1334     break;
1335 
1336   case AtomicExpr::AO__c11_atomic_store:
1337   case AtomicExpr::AO__atomic_load:
1338   case AtomicExpr::AO__atomic_store:
1339   case AtomicExpr::AO__atomic_store_n:
1340     Form = Copy;
1341     break;
1342 
1343   case AtomicExpr::AO__c11_atomic_fetch_add:
1344   case AtomicExpr::AO__c11_atomic_fetch_sub:
1345   case AtomicExpr::AO__atomic_fetch_add:
1346   case AtomicExpr::AO__atomic_fetch_sub:
1347   case AtomicExpr::AO__atomic_add_fetch:
1348   case AtomicExpr::AO__atomic_sub_fetch:
1349     IsAddSub = true;
1350     // Fall through.
1351   case AtomicExpr::AO__c11_atomic_fetch_and:
1352   case AtomicExpr::AO__c11_atomic_fetch_or:
1353   case AtomicExpr::AO__c11_atomic_fetch_xor:
1354   case AtomicExpr::AO__atomic_fetch_and:
1355   case AtomicExpr::AO__atomic_fetch_or:
1356   case AtomicExpr::AO__atomic_fetch_xor:
1357   case AtomicExpr::AO__atomic_fetch_nand:
1358   case AtomicExpr::AO__atomic_and_fetch:
1359   case AtomicExpr::AO__atomic_or_fetch:
1360   case AtomicExpr::AO__atomic_xor_fetch:
1361   case AtomicExpr::AO__atomic_nand_fetch:
1362     Form = Arithmetic;
1363     break;
1364 
1365   case AtomicExpr::AO__c11_atomic_exchange:
1366   case AtomicExpr::AO__atomic_exchange_n:
1367     Form = Xchg;
1368     break;
1369 
1370   case AtomicExpr::AO__atomic_exchange:
1371     Form = GNUXchg;
1372     break;
1373 
1374   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1375   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1376     Form = C11CmpXchg;
1377     break;
1378 
1379   case AtomicExpr::AO__atomic_compare_exchange:
1380   case AtomicExpr::AO__atomic_compare_exchange_n:
1381     Form = GNUCmpXchg;
1382     break;
1383   }
1384 
1385   // Check we have the right number of arguments.
1386   if (TheCall->getNumArgs() < NumArgs[Form]) {
1387     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1388       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1389       << TheCall->getCallee()->getSourceRange();
1390     return ExprError();
1391   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1392     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
1393          diag::err_typecheck_call_too_many_args)
1394       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1395       << TheCall->getCallee()->getSourceRange();
1396     return ExprError();
1397   }
1398 
1399   // Inspect the first argument of the atomic operation.
1400   Expr *Ptr = TheCall->getArg(0);
1401   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1402   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1403   if (!pointerType) {
1404     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1405       << Ptr->getType() << Ptr->getSourceRange();
1406     return ExprError();
1407   }
1408 
1409   // For a __c11 builtin, this should be a pointer to an _Atomic type.
1410   QualType AtomTy = pointerType->getPointeeType(); // 'A'
1411   QualType ValType = AtomTy; // 'C'
1412   if (IsC11) {
1413     if (!AtomTy->isAtomicType()) {
1414       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1415         << Ptr->getType() << Ptr->getSourceRange();
1416       return ExprError();
1417     }
1418     if (AtomTy.isConstQualified()) {
1419       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1420         << Ptr->getType() << Ptr->getSourceRange();
1421       return ExprError();
1422     }
1423     ValType = AtomTy->getAs<AtomicType>()->getValueType();
1424   }
1425 
1426   // For an arithmetic operation, the implied arithmetic must be well-formed.
1427   if (Form == Arithmetic) {
1428     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1429     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1430       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1431         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1432       return ExprError();
1433     }
1434     if (!IsAddSub && !ValType->isIntegerType()) {
1435       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1436         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1437       return ExprError();
1438     }
1439     if (IsC11 && ValType->isPointerType() &&
1440         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1441                             diag::err_incomplete_type)) {
1442       return ExprError();
1443     }
1444   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1445     // For __atomic_*_n operations, the value type must be a scalar integral or
1446     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1447     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1448       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1449     return ExprError();
1450   }
1451 
1452   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1453       !AtomTy->isScalarType()) {
1454     // For GNU atomics, require a trivially-copyable type. This is not part of
1455     // the GNU atomics specification, but we enforce it for sanity.
1456     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1457       << Ptr->getType() << Ptr->getSourceRange();
1458     return ExprError();
1459   }
1460 
1461   // FIXME: For any builtin other than a load, the ValType must not be
1462   // const-qualified.
1463 
1464   switch (ValType.getObjCLifetime()) {
1465   case Qualifiers::OCL_None:
1466   case Qualifiers::OCL_ExplicitNone:
1467     // okay
1468     break;
1469 
1470   case Qualifiers::OCL_Weak:
1471   case Qualifiers::OCL_Strong:
1472   case Qualifiers::OCL_Autoreleasing:
1473     // FIXME: Can this happen? By this point, ValType should be known
1474     // to be trivially copyable.
1475     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1476       << ValType << Ptr->getSourceRange();
1477     return ExprError();
1478   }
1479 
1480   QualType ResultType = ValType;
1481   if (Form == Copy || Form == GNUXchg || Form == Init)
1482     ResultType = Context.VoidTy;
1483   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1484     ResultType = Context.BoolTy;
1485 
1486   // The type of a parameter passed 'by value'. In the GNU atomics, such
1487   // arguments are actually passed as pointers.
1488   QualType ByValType = ValType; // 'CP'
1489   if (!IsC11 && !IsN)
1490     ByValType = Ptr->getType();
1491 
1492   // The first argument --- the pointer --- has a fixed type; we
1493   // deduce the types of the rest of the arguments accordingly.  Walk
1494   // the remaining arguments, converting them to the deduced value type.
1495   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1496     QualType Ty;
1497     if (i < NumVals[Form] + 1) {
1498       switch (i) {
1499       case 1:
1500         // The second argument is the non-atomic operand. For arithmetic, this
1501         // is always passed by value, and for a compare_exchange it is always
1502         // passed by address. For the rest, GNU uses by-address and C11 uses
1503         // by-value.
1504         assert(Form != Load);
1505         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1506           Ty = ValType;
1507         else if (Form == Copy || Form == Xchg)
1508           Ty = ByValType;
1509         else if (Form == Arithmetic)
1510           Ty = Context.getPointerDiffType();
1511         else
1512           Ty = Context.getPointerType(ValType.getUnqualifiedType());
1513         break;
1514       case 2:
1515         // The third argument to compare_exchange / GNU exchange is a
1516         // (pointer to a) desired value.
1517         Ty = ByValType;
1518         break;
1519       case 3:
1520         // The fourth argument to GNU compare_exchange is a 'weak' flag.
1521         Ty = Context.BoolTy;
1522         break;
1523       }
1524     } else {
1525       // The order(s) are always converted to int.
1526       Ty = Context.IntTy;
1527     }
1528 
1529     InitializedEntity Entity =
1530         InitializedEntity::InitializeParameter(Context, Ty, false);
1531     ExprResult Arg = TheCall->getArg(i);
1532     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1533     if (Arg.isInvalid())
1534       return true;
1535     TheCall->setArg(i, Arg.get());
1536   }
1537 
1538   // Permute the arguments into a 'consistent' order.
1539   SmallVector<Expr*, 5> SubExprs;
1540   SubExprs.push_back(Ptr);
1541   switch (Form) {
1542   case Init:
1543     // Note, AtomicExpr::getVal1() has a special case for this atomic.
1544     SubExprs.push_back(TheCall->getArg(1)); // Val1
1545     break;
1546   case Load:
1547     SubExprs.push_back(TheCall->getArg(1)); // Order
1548     break;
1549   case Copy:
1550   case Arithmetic:
1551   case Xchg:
1552     SubExprs.push_back(TheCall->getArg(2)); // Order
1553     SubExprs.push_back(TheCall->getArg(1)); // Val1
1554     break;
1555   case GNUXchg:
1556     // Note, AtomicExpr::getVal2() has a special case for this atomic.
1557     SubExprs.push_back(TheCall->getArg(3)); // Order
1558     SubExprs.push_back(TheCall->getArg(1)); // Val1
1559     SubExprs.push_back(TheCall->getArg(2)); // Val2
1560     break;
1561   case C11CmpXchg:
1562     SubExprs.push_back(TheCall->getArg(3)); // Order
1563     SubExprs.push_back(TheCall->getArg(1)); // Val1
1564     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1565     SubExprs.push_back(TheCall->getArg(2)); // Val2
1566     break;
1567   case GNUCmpXchg:
1568     SubExprs.push_back(TheCall->getArg(4)); // Order
1569     SubExprs.push_back(TheCall->getArg(1)); // Val1
1570     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1571     SubExprs.push_back(TheCall->getArg(2)); // Val2
1572     SubExprs.push_back(TheCall->getArg(3)); // Weak
1573     break;
1574   }
1575 
1576   if (SubExprs.size() >= 2 && Form != Init) {
1577     llvm::APSInt Result(32);
1578     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
1579         !isValidOrderingForOp(Result.getSExtValue(), Op))
1580       Diag(SubExprs[1]->getLocStart(),
1581            diag::warn_atomic_op_has_invalid_memory_order)
1582           << SubExprs[1]->getSourceRange();
1583   }
1584 
1585   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1586                                             SubExprs, ResultType, Op,
1587                                             TheCall->getRParenLoc());
1588 
1589   if ((Op == AtomicExpr::AO__c11_atomic_load ||
1590        (Op == AtomicExpr::AO__c11_atomic_store)) &&
1591       Context.AtomicUsesUnsupportedLibcall(AE))
1592     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1593     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1594 
1595   return AE;
1596 }
1597 
1598 
1599 /// checkBuiltinArgument - Given a call to a builtin function, perform
1600 /// normal type-checking on the given argument, updating the call in
1601 /// place.  This is useful when a builtin function requires custom
1602 /// type-checking for some of its arguments but not necessarily all of
1603 /// them.
1604 ///
1605 /// Returns true on error.
1606 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1607   FunctionDecl *Fn = E->getDirectCallee();
1608   assert(Fn && "builtin call without direct callee!");
1609 
1610   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1611   InitializedEntity Entity =
1612     InitializedEntity::InitializeParameter(S.Context, Param);
1613 
1614   ExprResult Arg = E->getArg(0);
1615   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1616   if (Arg.isInvalid())
1617     return true;
1618 
1619   E->setArg(ArgIndex, Arg.get());
1620   return false;
1621 }
1622 
1623 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
1624 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
1625 /// type of its first argument.  The main ActOnCallExpr routines have already
1626 /// promoted the types of arguments because all of these calls are prototyped as
1627 /// void(...).
1628 ///
1629 /// This function goes through and does final semantic checking for these
1630 /// builtins,
1631 ExprResult
1632 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1633   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1634   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1635   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1636 
1637   // Ensure that we have at least one argument to do type inference from.
1638   if (TheCall->getNumArgs() < 1) {
1639     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1640       << 0 << 1 << TheCall->getNumArgs()
1641       << TheCall->getCallee()->getSourceRange();
1642     return ExprError();
1643   }
1644 
1645   // Inspect the first argument of the atomic builtin.  This should always be
1646   // a pointer type, whose element is an integral scalar or pointer type.
1647   // Because it is a pointer type, we don't have to worry about any implicit
1648   // casts here.
1649   // FIXME: We don't allow floating point scalars as input.
1650   Expr *FirstArg = TheCall->getArg(0);
1651   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1652   if (FirstArgResult.isInvalid())
1653     return ExprError();
1654   FirstArg = FirstArgResult.get();
1655   TheCall->setArg(0, FirstArg);
1656 
1657   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1658   if (!pointerType) {
1659     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1660       << FirstArg->getType() << FirstArg->getSourceRange();
1661     return ExprError();
1662   }
1663 
1664   QualType ValType = pointerType->getPointeeType();
1665   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1666       !ValType->isBlockPointerType()) {
1667     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1668       << FirstArg->getType() << FirstArg->getSourceRange();
1669     return ExprError();
1670   }
1671 
1672   switch (ValType.getObjCLifetime()) {
1673   case Qualifiers::OCL_None:
1674   case Qualifiers::OCL_ExplicitNone:
1675     // okay
1676     break;
1677 
1678   case Qualifiers::OCL_Weak:
1679   case Qualifiers::OCL_Strong:
1680   case Qualifiers::OCL_Autoreleasing:
1681     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1682       << ValType << FirstArg->getSourceRange();
1683     return ExprError();
1684   }
1685 
1686   // Strip any qualifiers off ValType.
1687   ValType = ValType.getUnqualifiedType();
1688 
1689   // The majority of builtins return a value, but a few have special return
1690   // types, so allow them to override appropriately below.
1691   QualType ResultType = ValType;
1692 
1693   // We need to figure out which concrete builtin this maps onto.  For example,
1694   // __sync_fetch_and_add with a 2 byte object turns into
1695   // __sync_fetch_and_add_2.
1696 #define BUILTIN_ROW(x) \
1697   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1698     Builtin::BI##x##_8, Builtin::BI##x##_16 }
1699 
1700   static const unsigned BuiltinIndices[][5] = {
1701     BUILTIN_ROW(__sync_fetch_and_add),
1702     BUILTIN_ROW(__sync_fetch_and_sub),
1703     BUILTIN_ROW(__sync_fetch_and_or),
1704     BUILTIN_ROW(__sync_fetch_and_and),
1705     BUILTIN_ROW(__sync_fetch_and_xor),
1706     BUILTIN_ROW(__sync_fetch_and_nand),
1707 
1708     BUILTIN_ROW(__sync_add_and_fetch),
1709     BUILTIN_ROW(__sync_sub_and_fetch),
1710     BUILTIN_ROW(__sync_and_and_fetch),
1711     BUILTIN_ROW(__sync_or_and_fetch),
1712     BUILTIN_ROW(__sync_xor_and_fetch),
1713     BUILTIN_ROW(__sync_nand_and_fetch),
1714 
1715     BUILTIN_ROW(__sync_val_compare_and_swap),
1716     BUILTIN_ROW(__sync_bool_compare_and_swap),
1717     BUILTIN_ROW(__sync_lock_test_and_set),
1718     BUILTIN_ROW(__sync_lock_release),
1719     BUILTIN_ROW(__sync_swap)
1720   };
1721 #undef BUILTIN_ROW
1722 
1723   // Determine the index of the size.
1724   unsigned SizeIndex;
1725   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1726   case 1: SizeIndex = 0; break;
1727   case 2: SizeIndex = 1; break;
1728   case 4: SizeIndex = 2; break;
1729   case 8: SizeIndex = 3; break;
1730   case 16: SizeIndex = 4; break;
1731   default:
1732     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1733       << FirstArg->getType() << FirstArg->getSourceRange();
1734     return ExprError();
1735   }
1736 
1737   // Each of these builtins has one pointer argument, followed by some number of
1738   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1739   // that we ignore.  Find out which row of BuiltinIndices to read from as well
1740   // as the number of fixed args.
1741   unsigned BuiltinID = FDecl->getBuiltinID();
1742   unsigned BuiltinIndex, NumFixed = 1;
1743   bool WarnAboutSemanticsChange = false;
1744   switch (BuiltinID) {
1745   default: llvm_unreachable("Unknown overloaded atomic builtin!");
1746   case Builtin::BI__sync_fetch_and_add:
1747   case Builtin::BI__sync_fetch_and_add_1:
1748   case Builtin::BI__sync_fetch_and_add_2:
1749   case Builtin::BI__sync_fetch_and_add_4:
1750   case Builtin::BI__sync_fetch_and_add_8:
1751   case Builtin::BI__sync_fetch_and_add_16:
1752     BuiltinIndex = 0;
1753     break;
1754 
1755   case Builtin::BI__sync_fetch_and_sub:
1756   case Builtin::BI__sync_fetch_and_sub_1:
1757   case Builtin::BI__sync_fetch_and_sub_2:
1758   case Builtin::BI__sync_fetch_and_sub_4:
1759   case Builtin::BI__sync_fetch_and_sub_8:
1760   case Builtin::BI__sync_fetch_and_sub_16:
1761     BuiltinIndex = 1;
1762     break;
1763 
1764   case Builtin::BI__sync_fetch_and_or:
1765   case Builtin::BI__sync_fetch_and_or_1:
1766   case Builtin::BI__sync_fetch_and_or_2:
1767   case Builtin::BI__sync_fetch_and_or_4:
1768   case Builtin::BI__sync_fetch_and_or_8:
1769   case Builtin::BI__sync_fetch_and_or_16:
1770     BuiltinIndex = 2;
1771     break;
1772 
1773   case Builtin::BI__sync_fetch_and_and:
1774   case Builtin::BI__sync_fetch_and_and_1:
1775   case Builtin::BI__sync_fetch_and_and_2:
1776   case Builtin::BI__sync_fetch_and_and_4:
1777   case Builtin::BI__sync_fetch_and_and_8:
1778   case Builtin::BI__sync_fetch_and_and_16:
1779     BuiltinIndex = 3;
1780     break;
1781 
1782   case Builtin::BI__sync_fetch_and_xor:
1783   case Builtin::BI__sync_fetch_and_xor_1:
1784   case Builtin::BI__sync_fetch_and_xor_2:
1785   case Builtin::BI__sync_fetch_and_xor_4:
1786   case Builtin::BI__sync_fetch_and_xor_8:
1787   case Builtin::BI__sync_fetch_and_xor_16:
1788     BuiltinIndex = 4;
1789     break;
1790 
1791   case Builtin::BI__sync_fetch_and_nand:
1792   case Builtin::BI__sync_fetch_and_nand_1:
1793   case Builtin::BI__sync_fetch_and_nand_2:
1794   case Builtin::BI__sync_fetch_and_nand_4:
1795   case Builtin::BI__sync_fetch_and_nand_8:
1796   case Builtin::BI__sync_fetch_and_nand_16:
1797     BuiltinIndex = 5;
1798     WarnAboutSemanticsChange = true;
1799     break;
1800 
1801   case Builtin::BI__sync_add_and_fetch:
1802   case Builtin::BI__sync_add_and_fetch_1:
1803   case Builtin::BI__sync_add_and_fetch_2:
1804   case Builtin::BI__sync_add_and_fetch_4:
1805   case Builtin::BI__sync_add_and_fetch_8:
1806   case Builtin::BI__sync_add_and_fetch_16:
1807     BuiltinIndex = 6;
1808     break;
1809 
1810   case Builtin::BI__sync_sub_and_fetch:
1811   case Builtin::BI__sync_sub_and_fetch_1:
1812   case Builtin::BI__sync_sub_and_fetch_2:
1813   case Builtin::BI__sync_sub_and_fetch_4:
1814   case Builtin::BI__sync_sub_and_fetch_8:
1815   case Builtin::BI__sync_sub_and_fetch_16:
1816     BuiltinIndex = 7;
1817     break;
1818 
1819   case Builtin::BI__sync_and_and_fetch:
1820   case Builtin::BI__sync_and_and_fetch_1:
1821   case Builtin::BI__sync_and_and_fetch_2:
1822   case Builtin::BI__sync_and_and_fetch_4:
1823   case Builtin::BI__sync_and_and_fetch_8:
1824   case Builtin::BI__sync_and_and_fetch_16:
1825     BuiltinIndex = 8;
1826     break;
1827 
1828   case Builtin::BI__sync_or_and_fetch:
1829   case Builtin::BI__sync_or_and_fetch_1:
1830   case Builtin::BI__sync_or_and_fetch_2:
1831   case Builtin::BI__sync_or_and_fetch_4:
1832   case Builtin::BI__sync_or_and_fetch_8:
1833   case Builtin::BI__sync_or_and_fetch_16:
1834     BuiltinIndex = 9;
1835     break;
1836 
1837   case Builtin::BI__sync_xor_and_fetch:
1838   case Builtin::BI__sync_xor_and_fetch_1:
1839   case Builtin::BI__sync_xor_and_fetch_2:
1840   case Builtin::BI__sync_xor_and_fetch_4:
1841   case Builtin::BI__sync_xor_and_fetch_8:
1842   case Builtin::BI__sync_xor_and_fetch_16:
1843     BuiltinIndex = 10;
1844     break;
1845 
1846   case Builtin::BI__sync_nand_and_fetch:
1847   case Builtin::BI__sync_nand_and_fetch_1:
1848   case Builtin::BI__sync_nand_and_fetch_2:
1849   case Builtin::BI__sync_nand_and_fetch_4:
1850   case Builtin::BI__sync_nand_and_fetch_8:
1851   case Builtin::BI__sync_nand_and_fetch_16:
1852     BuiltinIndex = 11;
1853     WarnAboutSemanticsChange = true;
1854     break;
1855 
1856   case Builtin::BI__sync_val_compare_and_swap:
1857   case Builtin::BI__sync_val_compare_and_swap_1:
1858   case Builtin::BI__sync_val_compare_and_swap_2:
1859   case Builtin::BI__sync_val_compare_and_swap_4:
1860   case Builtin::BI__sync_val_compare_and_swap_8:
1861   case Builtin::BI__sync_val_compare_and_swap_16:
1862     BuiltinIndex = 12;
1863     NumFixed = 2;
1864     break;
1865 
1866   case Builtin::BI__sync_bool_compare_and_swap:
1867   case Builtin::BI__sync_bool_compare_and_swap_1:
1868   case Builtin::BI__sync_bool_compare_and_swap_2:
1869   case Builtin::BI__sync_bool_compare_and_swap_4:
1870   case Builtin::BI__sync_bool_compare_and_swap_8:
1871   case Builtin::BI__sync_bool_compare_and_swap_16:
1872     BuiltinIndex = 13;
1873     NumFixed = 2;
1874     ResultType = Context.BoolTy;
1875     break;
1876 
1877   case Builtin::BI__sync_lock_test_and_set:
1878   case Builtin::BI__sync_lock_test_and_set_1:
1879   case Builtin::BI__sync_lock_test_and_set_2:
1880   case Builtin::BI__sync_lock_test_and_set_4:
1881   case Builtin::BI__sync_lock_test_and_set_8:
1882   case Builtin::BI__sync_lock_test_and_set_16:
1883     BuiltinIndex = 14;
1884     break;
1885 
1886   case Builtin::BI__sync_lock_release:
1887   case Builtin::BI__sync_lock_release_1:
1888   case Builtin::BI__sync_lock_release_2:
1889   case Builtin::BI__sync_lock_release_4:
1890   case Builtin::BI__sync_lock_release_8:
1891   case Builtin::BI__sync_lock_release_16:
1892     BuiltinIndex = 15;
1893     NumFixed = 0;
1894     ResultType = Context.VoidTy;
1895     break;
1896 
1897   case Builtin::BI__sync_swap:
1898   case Builtin::BI__sync_swap_1:
1899   case Builtin::BI__sync_swap_2:
1900   case Builtin::BI__sync_swap_4:
1901   case Builtin::BI__sync_swap_8:
1902   case Builtin::BI__sync_swap_16:
1903     BuiltinIndex = 16;
1904     break;
1905   }
1906 
1907   // Now that we know how many fixed arguments we expect, first check that we
1908   // have at least that many.
1909   if (TheCall->getNumArgs() < 1+NumFixed) {
1910     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1911       << 0 << 1+NumFixed << TheCall->getNumArgs()
1912       << TheCall->getCallee()->getSourceRange();
1913     return ExprError();
1914   }
1915 
1916   if (WarnAboutSemanticsChange) {
1917     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
1918       << TheCall->getCallee()->getSourceRange();
1919   }
1920 
1921   // Get the decl for the concrete builtin from this, we can tell what the
1922   // concrete integer type we should convert to is.
1923   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1924   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1925   FunctionDecl *NewBuiltinDecl;
1926   if (NewBuiltinID == BuiltinID)
1927     NewBuiltinDecl = FDecl;
1928   else {
1929     // Perform builtin lookup to avoid redeclaring it.
1930     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1931     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1932     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1933     assert(Res.getFoundDecl());
1934     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1935     if (!NewBuiltinDecl)
1936       return ExprError();
1937   }
1938 
1939   // The first argument --- the pointer --- has a fixed type; we
1940   // deduce the types of the rest of the arguments accordingly.  Walk
1941   // the remaining arguments, converting them to the deduced value type.
1942   for (unsigned i = 0; i != NumFixed; ++i) {
1943     ExprResult Arg = TheCall->getArg(i+1);
1944 
1945     // GCC does an implicit conversion to the pointer or integer ValType.  This
1946     // can fail in some cases (1i -> int**), check for this error case now.
1947     // Initialize the argument.
1948     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1949                                                    ValType, /*consume*/ false);
1950     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1951     if (Arg.isInvalid())
1952       return ExprError();
1953 
1954     // Okay, we have something that *can* be converted to the right type.  Check
1955     // to see if there is a potentially weird extension going on here.  This can
1956     // happen when you do an atomic operation on something like an char* and
1957     // pass in 42.  The 42 gets converted to char.  This is even more strange
1958     // for things like 45.123 -> char, etc.
1959     // FIXME: Do this check.
1960     TheCall->setArg(i+1, Arg.get());
1961   }
1962 
1963   ASTContext& Context = this->getASTContext();
1964 
1965   // Create a new DeclRefExpr to refer to the new decl.
1966   DeclRefExpr* NewDRE = DeclRefExpr::Create(
1967       Context,
1968       DRE->getQualifierLoc(),
1969       SourceLocation(),
1970       NewBuiltinDecl,
1971       /*enclosing*/ false,
1972       DRE->getLocation(),
1973       Context.BuiltinFnTy,
1974       DRE->getValueKind());
1975 
1976   // Set the callee in the CallExpr.
1977   // FIXME: This loses syntactic information.
1978   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1979   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1980                                               CK_BuiltinFnToFnPtr);
1981   TheCall->setCallee(PromotedCall.get());
1982 
1983   // Change the result type of the call to match the original value type. This
1984   // is arbitrary, but the codegen for these builtins ins design to handle it
1985   // gracefully.
1986   TheCall->setType(ResultType);
1987 
1988   return TheCallResult;
1989 }
1990 
1991 /// CheckObjCString - Checks that the argument to the builtin
1992 /// CFString constructor is correct
1993 /// Note: It might also make sense to do the UTF-16 conversion here (would
1994 /// simplify the backend).
1995 bool Sema::CheckObjCString(Expr *Arg) {
1996   Arg = Arg->IgnoreParenCasts();
1997   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1998 
1999   if (!Literal || !Literal->isAscii()) {
2000     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2001       << Arg->getSourceRange();
2002     return true;
2003   }
2004 
2005   if (Literal->containsNonAsciiOrNull()) {
2006     StringRef String = Literal->getString();
2007     unsigned NumBytes = String.size();
2008     SmallVector<UTF16, 128> ToBuf(NumBytes);
2009     const UTF8 *FromPtr = (const UTF8 *)String.data();
2010     UTF16 *ToPtr = &ToBuf[0];
2011 
2012     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2013                                                  &ToPtr, ToPtr + NumBytes,
2014                                                  strictConversion);
2015     // Check for conversion failure.
2016     if (Result != conversionOK)
2017       Diag(Arg->getLocStart(),
2018            diag::warn_cfstring_truncated) << Arg->getSourceRange();
2019   }
2020   return false;
2021 }
2022 
2023 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
2024 /// Emit an error and return true on failure, return false on success.
2025 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2026   Expr *Fn = TheCall->getCallee();
2027   if (TheCall->getNumArgs() > 2) {
2028     Diag(TheCall->getArg(2)->getLocStart(),
2029          diag::err_typecheck_call_too_many_args)
2030       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2031       << Fn->getSourceRange()
2032       << SourceRange(TheCall->getArg(2)->getLocStart(),
2033                      (*(TheCall->arg_end()-1))->getLocEnd());
2034     return true;
2035   }
2036 
2037   if (TheCall->getNumArgs() < 2) {
2038     return Diag(TheCall->getLocEnd(),
2039       diag::err_typecheck_call_too_few_args_at_least)
2040       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
2041   }
2042 
2043   // Type-check the first argument normally.
2044   if (checkBuiltinArgument(*this, TheCall, 0))
2045     return true;
2046 
2047   // Determine whether the current function is variadic or not.
2048   BlockScopeInfo *CurBlock = getCurBlock();
2049   bool isVariadic;
2050   if (CurBlock)
2051     isVariadic = CurBlock->TheDecl->isVariadic();
2052   else if (FunctionDecl *FD = getCurFunctionDecl())
2053     isVariadic = FD->isVariadic();
2054   else
2055     isVariadic = getCurMethodDecl()->isVariadic();
2056 
2057   if (!isVariadic) {
2058     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2059     return true;
2060   }
2061 
2062   // Verify that the second argument to the builtin is the last argument of the
2063   // current function or method.
2064   bool SecondArgIsLastNamedArgument = false;
2065   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
2066 
2067   // These are valid if SecondArgIsLastNamedArgument is false after the next
2068   // block.
2069   QualType Type;
2070   SourceLocation ParamLoc;
2071 
2072   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2073     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
2074       // FIXME: This isn't correct for methods (results in bogus warning).
2075       // Get the last formal in the current function.
2076       const ParmVarDecl *LastArg;
2077       if (CurBlock)
2078         LastArg = *(CurBlock->TheDecl->param_end()-1);
2079       else if (FunctionDecl *FD = getCurFunctionDecl())
2080         LastArg = *(FD->param_end()-1);
2081       else
2082         LastArg = *(getCurMethodDecl()->param_end()-1);
2083       SecondArgIsLastNamedArgument = PV == LastArg;
2084 
2085       Type = PV->getType();
2086       ParamLoc = PV->getLocation();
2087     }
2088   }
2089 
2090   if (!SecondArgIsLastNamedArgument)
2091     Diag(TheCall->getArg(1)->getLocStart(),
2092          diag::warn_second_parameter_of_va_start_not_last_named_argument);
2093   else if (Type->isReferenceType()) {
2094     Diag(Arg->getLocStart(),
2095          diag::warn_va_start_of_reference_type_is_undefined);
2096     Diag(ParamLoc, diag::note_parameter_type) << Type;
2097   }
2098 
2099   TheCall->setType(Context.VoidTy);
2100   return false;
2101 }
2102 
2103 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2104   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2105   //                 const char *named_addr);
2106 
2107   Expr *Func = Call->getCallee();
2108 
2109   if (Call->getNumArgs() < 3)
2110     return Diag(Call->getLocEnd(),
2111                 diag::err_typecheck_call_too_few_args_at_least)
2112            << 0 /*function call*/ << 3 << Call->getNumArgs();
2113 
2114   // Determine whether the current function is variadic or not.
2115   bool IsVariadic;
2116   if (BlockScopeInfo *CurBlock = getCurBlock())
2117     IsVariadic = CurBlock->TheDecl->isVariadic();
2118   else if (FunctionDecl *FD = getCurFunctionDecl())
2119     IsVariadic = FD->isVariadic();
2120   else if (ObjCMethodDecl *MD = getCurMethodDecl())
2121     IsVariadic = MD->isVariadic();
2122   else
2123     llvm_unreachable("unexpected statement type");
2124 
2125   if (!IsVariadic) {
2126     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2127     return true;
2128   }
2129 
2130   // Type-check the first argument normally.
2131   if (checkBuiltinArgument(*this, Call, 0))
2132     return true;
2133 
2134   static const struct {
2135     unsigned ArgNo;
2136     QualType Type;
2137   } ArgumentTypes[] = {
2138     { 1, Context.getPointerType(Context.CharTy.withConst()) },
2139     { 2, Context.getSizeType() },
2140   };
2141 
2142   for (const auto &AT : ArgumentTypes) {
2143     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2144     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2145       continue;
2146     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2147       << Arg->getType() << AT.Type << 1 /* different class */
2148       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2149       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2150   }
2151 
2152   return false;
2153 }
2154 
2155 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2156 /// friends.  This is declared to take (...), so we have to check everything.
2157 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2158   if (TheCall->getNumArgs() < 2)
2159     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2160       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
2161   if (TheCall->getNumArgs() > 2)
2162     return Diag(TheCall->getArg(2)->getLocStart(),
2163                 diag::err_typecheck_call_too_many_args)
2164       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2165       << SourceRange(TheCall->getArg(2)->getLocStart(),
2166                      (*(TheCall->arg_end()-1))->getLocEnd());
2167 
2168   ExprResult OrigArg0 = TheCall->getArg(0);
2169   ExprResult OrigArg1 = TheCall->getArg(1);
2170 
2171   // Do standard promotions between the two arguments, returning their common
2172   // type.
2173   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
2174   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2175     return true;
2176 
2177   // Make sure any conversions are pushed back into the call; this is
2178   // type safe since unordered compare builtins are declared as "_Bool
2179   // foo(...)".
2180   TheCall->setArg(0, OrigArg0.get());
2181   TheCall->setArg(1, OrigArg1.get());
2182 
2183   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
2184     return false;
2185 
2186   // If the common type isn't a real floating type, then the arguments were
2187   // invalid for this operation.
2188   if (Res.isNull() || !Res->isRealFloatingType())
2189     return Diag(OrigArg0.get()->getLocStart(),
2190                 diag::err_typecheck_call_invalid_ordered_compare)
2191       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2192       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
2193 
2194   return false;
2195 }
2196 
2197 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2198 /// __builtin_isnan and friends.  This is declared to take (...), so we have
2199 /// to check everything. We expect the last argument to be a floating point
2200 /// value.
2201 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2202   if (TheCall->getNumArgs() < NumArgs)
2203     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2204       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
2205   if (TheCall->getNumArgs() > NumArgs)
2206     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
2207                 diag::err_typecheck_call_too_many_args)
2208       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
2209       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
2210                      (*(TheCall->arg_end()-1))->getLocEnd());
2211 
2212   Expr *OrigArg = TheCall->getArg(NumArgs-1);
2213 
2214   if (OrigArg->isTypeDependent())
2215     return false;
2216 
2217   // This operation requires a non-_Complex floating-point number.
2218   if (!OrigArg->getType()->isRealFloatingType())
2219     return Diag(OrigArg->getLocStart(),
2220                 diag::err_typecheck_call_invalid_unary_fp)
2221       << OrigArg->getType() << OrigArg->getSourceRange();
2222 
2223   // If this is an implicit conversion from float -> double, remove it.
2224   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2225     Expr *CastArg = Cast->getSubExpr();
2226     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2227       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2228              "promotion from float to double is the only expected cast here");
2229       Cast->setSubExpr(nullptr);
2230       TheCall->setArg(NumArgs-1, CastArg);
2231     }
2232   }
2233 
2234   return false;
2235 }
2236 
2237 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2238 // This is declared to take (...), so we have to check everything.
2239 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
2240   if (TheCall->getNumArgs() < 2)
2241     return ExprError(Diag(TheCall->getLocEnd(),
2242                           diag::err_typecheck_call_too_few_args_at_least)
2243                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2244                      << TheCall->getSourceRange());
2245 
2246   // Determine which of the following types of shufflevector we're checking:
2247   // 1) unary, vector mask: (lhs, mask)
2248   // 2) binary, vector mask: (lhs, rhs, mask)
2249   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2250   QualType resType = TheCall->getArg(0)->getType();
2251   unsigned numElements = 0;
2252 
2253   if (!TheCall->getArg(0)->isTypeDependent() &&
2254       !TheCall->getArg(1)->isTypeDependent()) {
2255     QualType LHSType = TheCall->getArg(0)->getType();
2256     QualType RHSType = TheCall->getArg(1)->getType();
2257 
2258     if (!LHSType->isVectorType() || !RHSType->isVectorType())
2259       return ExprError(Diag(TheCall->getLocStart(),
2260                             diag::err_shufflevector_non_vector)
2261                        << SourceRange(TheCall->getArg(0)->getLocStart(),
2262                                       TheCall->getArg(1)->getLocEnd()));
2263 
2264     numElements = LHSType->getAs<VectorType>()->getNumElements();
2265     unsigned numResElements = TheCall->getNumArgs() - 2;
2266 
2267     // Check to see if we have a call with 2 vector arguments, the unary shuffle
2268     // with mask.  If so, verify that RHS is an integer vector type with the
2269     // same number of elts as lhs.
2270     if (TheCall->getNumArgs() == 2) {
2271       if (!RHSType->hasIntegerRepresentation() ||
2272           RHSType->getAs<VectorType>()->getNumElements() != numElements)
2273         return ExprError(Diag(TheCall->getLocStart(),
2274                               diag::err_shufflevector_incompatible_vector)
2275                          << SourceRange(TheCall->getArg(1)->getLocStart(),
2276                                         TheCall->getArg(1)->getLocEnd()));
2277     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
2278       return ExprError(Diag(TheCall->getLocStart(),
2279                             diag::err_shufflevector_incompatible_vector)
2280                        << SourceRange(TheCall->getArg(0)->getLocStart(),
2281                                       TheCall->getArg(1)->getLocEnd()));
2282     } else if (numElements != numResElements) {
2283       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
2284       resType = Context.getVectorType(eltType, numResElements,
2285                                       VectorType::GenericVector);
2286     }
2287   }
2288 
2289   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
2290     if (TheCall->getArg(i)->isTypeDependent() ||
2291         TheCall->getArg(i)->isValueDependent())
2292       continue;
2293 
2294     llvm::APSInt Result(32);
2295     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2296       return ExprError(Diag(TheCall->getLocStart(),
2297                             diag::err_shufflevector_nonconstant_argument)
2298                        << TheCall->getArg(i)->getSourceRange());
2299 
2300     // Allow -1 which will be translated to undef in the IR.
2301     if (Result.isSigned() && Result.isAllOnesValue())
2302       continue;
2303 
2304     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
2305       return ExprError(Diag(TheCall->getLocStart(),
2306                             diag::err_shufflevector_argument_too_large)
2307                        << TheCall->getArg(i)->getSourceRange());
2308   }
2309 
2310   SmallVector<Expr*, 32> exprs;
2311 
2312   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
2313     exprs.push_back(TheCall->getArg(i));
2314     TheCall->setArg(i, nullptr);
2315   }
2316 
2317   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
2318                                          TheCall->getCallee()->getLocStart(),
2319                                          TheCall->getRParenLoc());
2320 }
2321 
2322 /// SemaConvertVectorExpr - Handle __builtin_convertvector
2323 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
2324                                        SourceLocation BuiltinLoc,
2325                                        SourceLocation RParenLoc) {
2326   ExprValueKind VK = VK_RValue;
2327   ExprObjectKind OK = OK_Ordinary;
2328   QualType DstTy = TInfo->getType();
2329   QualType SrcTy = E->getType();
2330 
2331   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
2332     return ExprError(Diag(BuiltinLoc,
2333                           diag::err_convertvector_non_vector)
2334                      << E->getSourceRange());
2335   if (!DstTy->isVectorType() && !DstTy->isDependentType())
2336     return ExprError(Diag(BuiltinLoc,
2337                           diag::err_convertvector_non_vector_type));
2338 
2339   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
2340     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
2341     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
2342     if (SrcElts != DstElts)
2343       return ExprError(Diag(BuiltinLoc,
2344                             diag::err_convertvector_incompatible_vector)
2345                        << E->getSourceRange());
2346   }
2347 
2348   return new (Context)
2349       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
2350 }
2351 
2352 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
2353 // This is declared to take (const void*, ...) and can take two
2354 // optional constant int args.
2355 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
2356   unsigned NumArgs = TheCall->getNumArgs();
2357 
2358   if (NumArgs > 3)
2359     return Diag(TheCall->getLocEnd(),
2360              diag::err_typecheck_call_too_many_args_at_most)
2361              << 0 /*function call*/ << 3 << NumArgs
2362              << TheCall->getSourceRange();
2363 
2364   // Argument 0 is checked for us and the remaining arguments must be
2365   // constant integers.
2366   for (unsigned i = 1; i != NumArgs; ++i)
2367     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
2368       return true;
2369 
2370   return false;
2371 }
2372 
2373 /// SemaBuiltinAssume - Handle __assume (MS Extension).
2374 // __assume does not evaluate its arguments, and should warn if its argument
2375 // has side effects.
2376 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
2377   Expr *Arg = TheCall->getArg(0);
2378   if (Arg->isInstantiationDependent()) return false;
2379 
2380   if (Arg->HasSideEffects(Context))
2381     return Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2382       << Arg->getSourceRange()
2383       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
2384 
2385   return false;
2386 }
2387 
2388 /// Handle __builtin_assume_aligned. This is declared
2389 /// as (const void*, size_t, ...) and can take one optional constant int arg.
2390 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
2391   unsigned NumArgs = TheCall->getNumArgs();
2392 
2393   if (NumArgs > 3)
2394     return Diag(TheCall->getLocEnd(),
2395              diag::err_typecheck_call_too_many_args_at_most)
2396              << 0 /*function call*/ << 3 << NumArgs
2397              << TheCall->getSourceRange();
2398 
2399   // The alignment must be a constant integer.
2400   Expr *Arg = TheCall->getArg(1);
2401 
2402   // We can't check the value of a dependent argument.
2403   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
2404     llvm::APSInt Result;
2405     if (SemaBuiltinConstantArg(TheCall, 1, Result))
2406       return true;
2407 
2408     if (!Result.isPowerOf2())
2409       return Diag(TheCall->getLocStart(),
2410                   diag::err_alignment_not_power_of_two)
2411            << Arg->getSourceRange();
2412   }
2413 
2414   if (NumArgs > 2) {
2415     ExprResult Arg(TheCall->getArg(2));
2416     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2417       Context.getSizeType(), false);
2418     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2419     if (Arg.isInvalid()) return true;
2420     TheCall->setArg(2, Arg.get());
2421   }
2422 
2423   return false;
2424 }
2425 
2426 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
2427 /// TheCall is a constant expression.
2428 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
2429                                   llvm::APSInt &Result) {
2430   Expr *Arg = TheCall->getArg(ArgNum);
2431   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2432   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2433 
2434   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
2435 
2436   if (!Arg->isIntegerConstantExpr(Result, Context))
2437     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
2438                 << FDecl->getDeclName() <<  Arg->getSourceRange();
2439 
2440   return false;
2441 }
2442 
2443 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
2444 /// TheCall is a constant expression in the range [Low, High].
2445 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
2446                                        int Low, int High) {
2447   llvm::APSInt Result;
2448 
2449   // We can't check the value of a dependent argument.
2450   Expr *Arg = TheCall->getArg(ArgNum);
2451   if (Arg->isTypeDependent() || Arg->isValueDependent())
2452     return false;
2453 
2454   // Check constant-ness first.
2455   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2456     return true;
2457 
2458   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
2459     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
2460       << Low << High << Arg->getSourceRange();
2461 
2462   return false;
2463 }
2464 
2465 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
2466 /// This checks that val is a constant 1.
2467 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
2468   Expr *Arg = TheCall->getArg(1);
2469   llvm::APSInt Result;
2470 
2471   // TODO: This is less than ideal. Overload this to take a value.
2472   if (SemaBuiltinConstantArg(TheCall, 1, Result))
2473     return true;
2474 
2475   if (Result != 1)
2476     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
2477              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2478 
2479   return false;
2480 }
2481 
2482 namespace {
2483 enum StringLiteralCheckType {
2484   SLCT_NotALiteral,
2485   SLCT_UncheckedLiteral,
2486   SLCT_CheckedLiteral
2487 };
2488 }
2489 
2490 // Determine if an expression is a string literal or constant string.
2491 // If this function returns false on the arguments to a function expecting a
2492 // format string, we will usually need to emit a warning.
2493 // True string literals are then checked by CheckFormatString.
2494 static StringLiteralCheckType
2495 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
2496                       bool HasVAListArg, unsigned format_idx,
2497                       unsigned firstDataArg, Sema::FormatStringType Type,
2498                       Sema::VariadicCallType CallType, bool InFunctionCall,
2499                       llvm::SmallBitVector &CheckedVarArgs) {
2500  tryAgain:
2501   if (E->isTypeDependent() || E->isValueDependent())
2502     return SLCT_NotALiteral;
2503 
2504   E = E->IgnoreParenCasts();
2505 
2506   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
2507     // Technically -Wformat-nonliteral does not warn about this case.
2508     // The behavior of printf and friends in this case is implementation
2509     // dependent.  Ideally if the format string cannot be null then
2510     // it should have a 'nonnull' attribute in the function prototype.
2511     return SLCT_UncheckedLiteral;
2512 
2513   switch (E->getStmtClass()) {
2514   case Stmt::BinaryConditionalOperatorClass:
2515   case Stmt::ConditionalOperatorClass: {
2516     // The expression is a literal if both sub-expressions were, and it was
2517     // completely checked only if both sub-expressions were checked.
2518     const AbstractConditionalOperator *C =
2519         cast<AbstractConditionalOperator>(E);
2520     StringLiteralCheckType Left =
2521         checkFormatStringExpr(S, C->getTrueExpr(), Args,
2522                               HasVAListArg, format_idx, firstDataArg,
2523                               Type, CallType, InFunctionCall, CheckedVarArgs);
2524     if (Left == SLCT_NotALiteral)
2525       return SLCT_NotALiteral;
2526     StringLiteralCheckType Right =
2527         checkFormatStringExpr(S, C->getFalseExpr(), Args,
2528                               HasVAListArg, format_idx, firstDataArg,
2529                               Type, CallType, InFunctionCall, CheckedVarArgs);
2530     return Left < Right ? Left : Right;
2531   }
2532 
2533   case Stmt::ImplicitCastExprClass: {
2534     E = cast<ImplicitCastExpr>(E)->getSubExpr();
2535     goto tryAgain;
2536   }
2537 
2538   case Stmt::OpaqueValueExprClass:
2539     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2540       E = src;
2541       goto tryAgain;
2542     }
2543     return SLCT_NotALiteral;
2544 
2545   case Stmt::PredefinedExprClass:
2546     // While __func__, etc., are technically not string literals, they
2547     // cannot contain format specifiers and thus are not a security
2548     // liability.
2549     return SLCT_UncheckedLiteral;
2550 
2551   case Stmt::DeclRefExprClass: {
2552     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2553 
2554     // As an exception, do not flag errors for variables binding to
2555     // const string literals.
2556     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2557       bool isConstant = false;
2558       QualType T = DR->getType();
2559 
2560       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2561         isConstant = AT->getElementType().isConstant(S.Context);
2562       } else if (const PointerType *PT = T->getAs<PointerType>()) {
2563         isConstant = T.isConstant(S.Context) &&
2564                      PT->getPointeeType().isConstant(S.Context);
2565       } else if (T->isObjCObjectPointerType()) {
2566         // In ObjC, there is usually no "const ObjectPointer" type,
2567         // so don't check if the pointee type is constant.
2568         isConstant = T.isConstant(S.Context);
2569       }
2570 
2571       if (isConstant) {
2572         if (const Expr *Init = VD->getAnyInitializer()) {
2573           // Look through initializers like const char c[] = { "foo" }
2574           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2575             if (InitList->isStringLiteralInit())
2576               Init = InitList->getInit(0)->IgnoreParenImpCasts();
2577           }
2578           return checkFormatStringExpr(S, Init, Args,
2579                                        HasVAListArg, format_idx,
2580                                        firstDataArg, Type, CallType,
2581                                        /*InFunctionCall*/false, CheckedVarArgs);
2582         }
2583       }
2584 
2585       // For vprintf* functions (i.e., HasVAListArg==true), we add a
2586       // special check to see if the format string is a function parameter
2587       // of the function calling the printf function.  If the function
2588       // has an attribute indicating it is a printf-like function, then we
2589       // should suppress warnings concerning non-literals being used in a call
2590       // to a vprintf function.  For example:
2591       //
2592       // void
2593       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2594       //      va_list ap;
2595       //      va_start(ap, fmt);
2596       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
2597       //      ...
2598       // }
2599       if (HasVAListArg) {
2600         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2601           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2602             int PVIndex = PV->getFunctionScopeIndex() + 1;
2603             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
2604               // adjust for implicit parameter
2605               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2606                 if (MD->isInstance())
2607                   ++PVIndex;
2608               // We also check if the formats are compatible.
2609               // We can't pass a 'scanf' string to a 'printf' function.
2610               if (PVIndex == PVFormat->getFormatIdx() &&
2611                   Type == S.GetFormatStringType(PVFormat))
2612                 return SLCT_UncheckedLiteral;
2613             }
2614           }
2615         }
2616       }
2617     }
2618 
2619     return SLCT_NotALiteral;
2620   }
2621 
2622   case Stmt::CallExprClass:
2623   case Stmt::CXXMemberCallExprClass: {
2624     const CallExpr *CE = cast<CallExpr>(E);
2625     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2626       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2627         unsigned ArgIndex = FA->getFormatIdx();
2628         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2629           if (MD->isInstance())
2630             --ArgIndex;
2631         const Expr *Arg = CE->getArg(ArgIndex - 1);
2632 
2633         return checkFormatStringExpr(S, Arg, Args,
2634                                      HasVAListArg, format_idx, firstDataArg,
2635                                      Type, CallType, InFunctionCall,
2636                                      CheckedVarArgs);
2637       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2638         unsigned BuiltinID = FD->getBuiltinID();
2639         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2640             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2641           const Expr *Arg = CE->getArg(0);
2642           return checkFormatStringExpr(S, Arg, Args,
2643                                        HasVAListArg, format_idx,
2644                                        firstDataArg, Type, CallType,
2645                                        InFunctionCall, CheckedVarArgs);
2646         }
2647       }
2648     }
2649 
2650     return SLCT_NotALiteral;
2651   }
2652   case Stmt::ObjCStringLiteralClass:
2653   case Stmt::StringLiteralClass: {
2654     const StringLiteral *StrE = nullptr;
2655 
2656     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2657       StrE = ObjCFExpr->getString();
2658     else
2659       StrE = cast<StringLiteral>(E);
2660 
2661     if (StrE) {
2662       S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2663                           Type, InFunctionCall, CallType, CheckedVarArgs);
2664       return SLCT_CheckedLiteral;
2665     }
2666 
2667     return SLCT_NotALiteral;
2668   }
2669 
2670   default:
2671     return SLCT_NotALiteral;
2672   }
2673 }
2674 
2675 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2676   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
2677   .Case("scanf", FST_Scanf)
2678   .Cases("printf", "printf0", FST_Printf)
2679   .Cases("NSString", "CFString", FST_NSString)
2680   .Case("strftime", FST_Strftime)
2681   .Case("strfmon", FST_Strfmon)
2682   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2683   .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
2684   .Case("os_trace", FST_OSTrace)
2685   .Default(FST_Unknown);
2686 }
2687 
2688 /// CheckFormatArguments - Check calls to printf and scanf (and similar
2689 /// functions) for correct use of format strings.
2690 /// Returns true if a format string has been fully checked.
2691 bool Sema::CheckFormatArguments(const FormatAttr *Format,
2692                                 ArrayRef<const Expr *> Args,
2693                                 bool IsCXXMember,
2694                                 VariadicCallType CallType,
2695                                 SourceLocation Loc, SourceRange Range,
2696                                 llvm::SmallBitVector &CheckedVarArgs) {
2697   FormatStringInfo FSI;
2698   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
2699     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
2700                                 FSI.FirstDataArg, GetFormatStringType(Format),
2701                                 CallType, Loc, Range, CheckedVarArgs);
2702   return false;
2703 }
2704 
2705 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
2706                                 bool HasVAListArg, unsigned format_idx,
2707                                 unsigned firstDataArg, FormatStringType Type,
2708                                 VariadicCallType CallType,
2709                                 SourceLocation Loc, SourceRange Range,
2710                                 llvm::SmallBitVector &CheckedVarArgs) {
2711   // CHECK: printf/scanf-like function is called with no format string.
2712   if (format_idx >= Args.size()) {
2713     Diag(Loc, diag::warn_missing_format_string) << Range;
2714     return false;
2715   }
2716 
2717   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
2718 
2719   // CHECK: format string is not a string literal.
2720   //
2721   // Dynamically generated format strings are difficult to
2722   // automatically vet at compile time.  Requiring that format strings
2723   // are string literals: (1) permits the checking of format strings by
2724   // the compiler and thereby (2) can practically remove the source of
2725   // many format string exploits.
2726 
2727   // Format string can be either ObjC string (e.g. @"%d") or
2728   // C string (e.g. "%d")
2729   // ObjC string uses the same format specifiers as C string, so we can use
2730   // the same format string checking logic for both ObjC and C strings.
2731   StringLiteralCheckType CT =
2732       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2733                             format_idx, firstDataArg, Type, CallType,
2734                             /*IsFunctionCall*/true, CheckedVarArgs);
2735   if (CT != SLCT_NotALiteral)
2736     // Literal format string found, check done!
2737     return CT == SLCT_CheckedLiteral;
2738 
2739   // Strftime is particular as it always uses a single 'time' argument,
2740   // so it is safe to pass a non-literal string.
2741   if (Type == FST_Strftime)
2742     return false;
2743 
2744   // Do not emit diag when the string param is a macro expansion and the
2745   // format is either NSString or CFString. This is a hack to prevent
2746   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2747   // which are usually used in place of NS and CF string literals.
2748   if (Type == FST_NSString &&
2749       SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
2750     return false;
2751 
2752   // If there are no arguments specified, warn with -Wformat-security, otherwise
2753   // warn only with -Wformat-nonliteral.
2754   if (Args.size() == firstDataArg)
2755     Diag(Args[format_idx]->getLocStart(),
2756          diag::warn_format_nonliteral_noargs)
2757       << OrigFormatExpr->getSourceRange();
2758   else
2759     Diag(Args[format_idx]->getLocStart(),
2760          diag::warn_format_nonliteral)
2761            << OrigFormatExpr->getSourceRange();
2762   return false;
2763 }
2764 
2765 namespace {
2766 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2767 protected:
2768   Sema &S;
2769   const StringLiteral *FExpr;
2770   const Expr *OrigFormatExpr;
2771   const unsigned FirstDataArg;
2772   const unsigned NumDataArgs;
2773   const char *Beg; // Start of format string.
2774   const bool HasVAListArg;
2775   ArrayRef<const Expr *> Args;
2776   unsigned FormatIdx;
2777   llvm::SmallBitVector CoveredArgs;
2778   bool usesPositionalArgs;
2779   bool atFirstArg;
2780   bool inFunctionCall;
2781   Sema::VariadicCallType CallType;
2782   llvm::SmallBitVector &CheckedVarArgs;
2783 public:
2784   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2785                      const Expr *origFormatExpr, unsigned firstDataArg,
2786                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
2787                      ArrayRef<const Expr *> Args,
2788                      unsigned formatIdx, bool inFunctionCall,
2789                      Sema::VariadicCallType callType,
2790                      llvm::SmallBitVector &CheckedVarArgs)
2791     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2792       FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2793       Beg(beg), HasVAListArg(hasVAListArg),
2794       Args(Args), FormatIdx(formatIdx),
2795       usesPositionalArgs(false), atFirstArg(true),
2796       inFunctionCall(inFunctionCall), CallType(callType),
2797       CheckedVarArgs(CheckedVarArgs) {
2798     CoveredArgs.resize(numDataArgs);
2799     CoveredArgs.reset();
2800   }
2801 
2802   void DoneProcessing();
2803 
2804   void HandleIncompleteSpecifier(const char *startSpecifier,
2805                                  unsigned specifierLen) override;
2806 
2807   void HandleInvalidLengthModifier(
2808                            const analyze_format_string::FormatSpecifier &FS,
2809                            const analyze_format_string::ConversionSpecifier &CS,
2810                            const char *startSpecifier, unsigned specifierLen,
2811                            unsigned DiagID);
2812 
2813   void HandleNonStandardLengthModifier(
2814                     const analyze_format_string::FormatSpecifier &FS,
2815                     const char *startSpecifier, unsigned specifierLen);
2816 
2817   void HandleNonStandardConversionSpecifier(
2818                     const analyze_format_string::ConversionSpecifier &CS,
2819                     const char *startSpecifier, unsigned specifierLen);
2820 
2821   void HandlePosition(const char *startPos, unsigned posLen) override;
2822 
2823   void HandleInvalidPosition(const char *startSpecifier,
2824                              unsigned specifierLen,
2825                              analyze_format_string::PositionContext p) override;
2826 
2827   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
2828 
2829   void HandleNullChar(const char *nullCharacter) override;
2830 
2831   template <typename Range>
2832   static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2833                                    const Expr *ArgumentExpr,
2834                                    PartialDiagnostic PDiag,
2835                                    SourceLocation StringLoc,
2836                                    bool IsStringLocation, Range StringRange,
2837                                    ArrayRef<FixItHint> Fixit = None);
2838 
2839 protected:
2840   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2841                                         const char *startSpec,
2842                                         unsigned specifierLen,
2843                                         const char *csStart, unsigned csLen);
2844 
2845   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2846                                          const char *startSpec,
2847                                          unsigned specifierLen);
2848 
2849   SourceRange getFormatStringRange();
2850   CharSourceRange getSpecifierRange(const char *startSpecifier,
2851                                     unsigned specifierLen);
2852   SourceLocation getLocationOfByte(const char *x);
2853 
2854   const Expr *getDataArg(unsigned i) const;
2855 
2856   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2857                     const analyze_format_string::ConversionSpecifier &CS,
2858                     const char *startSpecifier, unsigned specifierLen,
2859                     unsigned argIndex);
2860 
2861   template <typename Range>
2862   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2863                             bool IsStringLocation, Range StringRange,
2864                             ArrayRef<FixItHint> Fixit = None);
2865 };
2866 }
2867 
2868 SourceRange CheckFormatHandler::getFormatStringRange() {
2869   return OrigFormatExpr->getSourceRange();
2870 }
2871 
2872 CharSourceRange CheckFormatHandler::
2873 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2874   SourceLocation Start = getLocationOfByte(startSpecifier);
2875   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
2876 
2877   // Advance the end SourceLocation by one due to half-open ranges.
2878   End = End.getLocWithOffset(1);
2879 
2880   return CharSourceRange::getCharRange(Start, End);
2881 }
2882 
2883 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2884   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2885 }
2886 
2887 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2888                                                    unsigned specifierLen){
2889   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2890                        getLocationOfByte(startSpecifier),
2891                        /*IsStringLocation*/true,
2892                        getSpecifierRange(startSpecifier, specifierLen));
2893 }
2894 
2895 void CheckFormatHandler::HandleInvalidLengthModifier(
2896     const analyze_format_string::FormatSpecifier &FS,
2897     const analyze_format_string::ConversionSpecifier &CS,
2898     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2899   using namespace analyze_format_string;
2900 
2901   const LengthModifier &LM = FS.getLengthModifier();
2902   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2903 
2904   // See if we know how to fix this length modifier.
2905   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2906   if (FixedLM) {
2907     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2908                          getLocationOfByte(LM.getStart()),
2909                          /*IsStringLocation*/true,
2910                          getSpecifierRange(startSpecifier, specifierLen));
2911 
2912     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2913       << FixedLM->toString()
2914       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2915 
2916   } else {
2917     FixItHint Hint;
2918     if (DiagID == diag::warn_format_nonsensical_length)
2919       Hint = FixItHint::CreateRemoval(LMRange);
2920 
2921     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2922                          getLocationOfByte(LM.getStart()),
2923                          /*IsStringLocation*/true,
2924                          getSpecifierRange(startSpecifier, specifierLen),
2925                          Hint);
2926   }
2927 }
2928 
2929 void CheckFormatHandler::HandleNonStandardLengthModifier(
2930     const analyze_format_string::FormatSpecifier &FS,
2931     const char *startSpecifier, unsigned specifierLen) {
2932   using namespace analyze_format_string;
2933 
2934   const LengthModifier &LM = FS.getLengthModifier();
2935   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2936 
2937   // See if we know how to fix this length modifier.
2938   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2939   if (FixedLM) {
2940     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2941                            << LM.toString() << 0,
2942                          getLocationOfByte(LM.getStart()),
2943                          /*IsStringLocation*/true,
2944                          getSpecifierRange(startSpecifier, specifierLen));
2945 
2946     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2947       << FixedLM->toString()
2948       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2949 
2950   } else {
2951     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2952                            << LM.toString() << 0,
2953                          getLocationOfByte(LM.getStart()),
2954                          /*IsStringLocation*/true,
2955                          getSpecifierRange(startSpecifier, specifierLen));
2956   }
2957 }
2958 
2959 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2960     const analyze_format_string::ConversionSpecifier &CS,
2961     const char *startSpecifier, unsigned specifierLen) {
2962   using namespace analyze_format_string;
2963 
2964   // See if we know how to fix this conversion specifier.
2965   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2966   if (FixedCS) {
2967     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2968                           << CS.toString() << /*conversion specifier*/1,
2969                          getLocationOfByte(CS.getStart()),
2970                          /*IsStringLocation*/true,
2971                          getSpecifierRange(startSpecifier, specifierLen));
2972 
2973     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2974     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2975       << FixedCS->toString()
2976       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2977   } else {
2978     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2979                           << CS.toString() << /*conversion specifier*/1,
2980                          getLocationOfByte(CS.getStart()),
2981                          /*IsStringLocation*/true,
2982                          getSpecifierRange(startSpecifier, specifierLen));
2983   }
2984 }
2985 
2986 void CheckFormatHandler::HandlePosition(const char *startPos,
2987                                         unsigned posLen) {
2988   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2989                                getLocationOfByte(startPos),
2990                                /*IsStringLocation*/true,
2991                                getSpecifierRange(startPos, posLen));
2992 }
2993 
2994 void
2995 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2996                                      analyze_format_string::PositionContext p) {
2997   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2998                          << (unsigned) p,
2999                        getLocationOfByte(startPos), /*IsStringLocation*/true,
3000                        getSpecifierRange(startPos, posLen));
3001 }
3002 
3003 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
3004                                             unsigned posLen) {
3005   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3006                                getLocationOfByte(startPos),
3007                                /*IsStringLocation*/true,
3008                                getSpecifierRange(startPos, posLen));
3009 }
3010 
3011 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
3012   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
3013     // The presence of a null character is likely an error.
3014     EmitFormatDiagnostic(
3015       S.PDiag(diag::warn_printf_format_string_contains_null_char),
3016       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3017       getFormatStringRange());
3018   }
3019 }
3020 
3021 // Note that this may return NULL if there was an error parsing or building
3022 // one of the argument expressions.
3023 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
3024   return Args[FirstDataArg + i];
3025 }
3026 
3027 void CheckFormatHandler::DoneProcessing() {
3028     // Does the number of data arguments exceed the number of
3029     // format conversions in the format string?
3030   if (!HasVAListArg) {
3031       // Find any arguments that weren't covered.
3032     CoveredArgs.flip();
3033     signed notCoveredArg = CoveredArgs.find_first();
3034     if (notCoveredArg >= 0) {
3035       assert((unsigned)notCoveredArg < NumDataArgs);
3036       if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
3037         SourceLocation Loc = E->getLocStart();
3038         if (!S.getSourceManager().isInSystemMacro(Loc)) {
3039           EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
3040                                Loc, /*IsStringLocation*/false,
3041                                getFormatStringRange());
3042         }
3043       }
3044     }
3045   }
3046 }
3047 
3048 bool
3049 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3050                                                      SourceLocation Loc,
3051                                                      const char *startSpec,
3052                                                      unsigned specifierLen,
3053                                                      const char *csStart,
3054                                                      unsigned csLen) {
3055 
3056   bool keepGoing = true;
3057   if (argIndex < NumDataArgs) {
3058     // Consider the argument coverered, even though the specifier doesn't
3059     // make sense.
3060     CoveredArgs.set(argIndex);
3061   }
3062   else {
3063     // If argIndex exceeds the number of data arguments we
3064     // don't issue a warning because that is just a cascade of warnings (and
3065     // they may have intended '%%' anyway). We don't want to continue processing
3066     // the format string after this point, however, as we will like just get
3067     // gibberish when trying to match arguments.
3068     keepGoing = false;
3069   }
3070 
3071   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
3072                          << StringRef(csStart, csLen),
3073                        Loc, /*IsStringLocation*/true,
3074                        getSpecifierRange(startSpec, specifierLen));
3075 
3076   return keepGoing;
3077 }
3078 
3079 void
3080 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
3081                                                       const char *startSpec,
3082                                                       unsigned specifierLen) {
3083   EmitFormatDiagnostic(
3084     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
3085     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
3086 }
3087 
3088 bool
3089 CheckFormatHandler::CheckNumArgs(
3090   const analyze_format_string::FormatSpecifier &FS,
3091   const analyze_format_string::ConversionSpecifier &CS,
3092   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
3093 
3094   if (argIndex >= NumDataArgs) {
3095     PartialDiagnostic PDiag = FS.usesPositionalArg()
3096       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3097            << (argIndex+1) << NumDataArgs)
3098       : S.PDiag(diag::warn_printf_insufficient_data_args);
3099     EmitFormatDiagnostic(
3100       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
3101       getSpecifierRange(startSpecifier, specifierLen));
3102     return false;
3103   }
3104   return true;
3105 }
3106 
3107 template<typename Range>
3108 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
3109                                               SourceLocation Loc,
3110                                               bool IsStringLocation,
3111                                               Range StringRange,
3112                                               ArrayRef<FixItHint> FixIt) {
3113   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
3114                        Loc, IsStringLocation, StringRange, FixIt);
3115 }
3116 
3117 /// \brief If the format string is not within the funcion call, emit a note
3118 /// so that the function call and string are in diagnostic messages.
3119 ///
3120 /// \param InFunctionCall if true, the format string is within the function
3121 /// call and only one diagnostic message will be produced.  Otherwise, an
3122 /// extra note will be emitted pointing to location of the format string.
3123 ///
3124 /// \param ArgumentExpr the expression that is passed as the format string
3125 /// argument in the function call.  Used for getting locations when two
3126 /// diagnostics are emitted.
3127 ///
3128 /// \param PDiag the callee should already have provided any strings for the
3129 /// diagnostic message.  This function only adds locations and fixits
3130 /// to diagnostics.
3131 ///
3132 /// \param Loc primary location for diagnostic.  If two diagnostics are
3133 /// required, one will be at Loc and a new SourceLocation will be created for
3134 /// the other one.
3135 ///
3136 /// \param IsStringLocation if true, Loc points to the format string should be
3137 /// used for the note.  Otherwise, Loc points to the argument list and will
3138 /// be used with PDiag.
3139 ///
3140 /// \param StringRange some or all of the string to highlight.  This is
3141 /// templated so it can accept either a CharSourceRange or a SourceRange.
3142 ///
3143 /// \param FixIt optional fix it hint for the format string.
3144 template<typename Range>
3145 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
3146                                               const Expr *ArgumentExpr,
3147                                               PartialDiagnostic PDiag,
3148                                               SourceLocation Loc,
3149                                               bool IsStringLocation,
3150                                               Range StringRange,
3151                                               ArrayRef<FixItHint> FixIt) {
3152   if (InFunctionCall) {
3153     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
3154     D << StringRange;
3155     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3156          I != E; ++I) {
3157       D << *I;
3158     }
3159   } else {
3160     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
3161       << ArgumentExpr->getSourceRange();
3162 
3163     const Sema::SemaDiagnosticBuilder &Note =
3164       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3165              diag::note_format_string_defined);
3166 
3167     Note << StringRange;
3168     for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
3169          I != E; ++I) {
3170       Note << *I;
3171     }
3172   }
3173 }
3174 
3175 //===--- CHECK: Printf format string checking ------------------------------===//
3176 
3177 namespace {
3178 class CheckPrintfHandler : public CheckFormatHandler {
3179   bool ObjCContext;
3180 public:
3181   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
3182                      const Expr *origFormatExpr, unsigned firstDataArg,
3183                      unsigned numDataArgs, bool isObjC,
3184                      const char *beg, bool hasVAListArg,
3185                      ArrayRef<const Expr *> Args,
3186                      unsigned formatIdx, bool inFunctionCall,
3187                      Sema::VariadicCallType CallType,
3188                      llvm::SmallBitVector &CheckedVarArgs)
3189     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3190                          numDataArgs, beg, hasVAListArg, Args,
3191                          formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3192       ObjCContext(isObjC)
3193   {}
3194 
3195 
3196   bool HandleInvalidPrintfConversionSpecifier(
3197                                       const analyze_printf::PrintfSpecifier &FS,
3198                                       const char *startSpecifier,
3199                                       unsigned specifierLen) override;
3200 
3201   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
3202                              const char *startSpecifier,
3203                              unsigned specifierLen) override;
3204   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3205                        const char *StartSpecifier,
3206                        unsigned SpecifierLen,
3207                        const Expr *E);
3208 
3209   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
3210                     const char *startSpecifier, unsigned specifierLen);
3211   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
3212                            const analyze_printf::OptionalAmount &Amt,
3213                            unsigned type,
3214                            const char *startSpecifier, unsigned specifierLen);
3215   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3216                   const analyze_printf::OptionalFlag &flag,
3217                   const char *startSpecifier, unsigned specifierLen);
3218   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
3219                          const analyze_printf::OptionalFlag &ignoredFlag,
3220                          const analyze_printf::OptionalFlag &flag,
3221                          const char *startSpecifier, unsigned specifierLen);
3222   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
3223                            const Expr *E);
3224 
3225 };
3226 }
3227 
3228 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3229                                       const analyze_printf::PrintfSpecifier &FS,
3230                                       const char *startSpecifier,
3231                                       unsigned specifierLen) {
3232   const analyze_printf::PrintfConversionSpecifier &CS =
3233     FS.getConversionSpecifier();
3234 
3235   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3236                                           getLocationOfByte(CS.getStart()),
3237                                           startSpecifier, specifierLen,
3238                                           CS.getStart(), CS.getLength());
3239 }
3240 
3241 bool CheckPrintfHandler::HandleAmount(
3242                                const analyze_format_string::OptionalAmount &Amt,
3243                                unsigned k, const char *startSpecifier,
3244                                unsigned specifierLen) {
3245 
3246   if (Amt.hasDataArgument()) {
3247     if (!HasVAListArg) {
3248       unsigned argIndex = Amt.getArgIndex();
3249       if (argIndex >= NumDataArgs) {
3250         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
3251                                << k,
3252                              getLocationOfByte(Amt.getStart()),
3253                              /*IsStringLocation*/true,
3254                              getSpecifierRange(startSpecifier, specifierLen));
3255         // Don't do any more checking.  We will just emit
3256         // spurious errors.
3257         return false;
3258       }
3259 
3260       // Type check the data argument.  It should be an 'int'.
3261       // Although not in conformance with C99, we also allow the argument to be
3262       // an 'unsigned int' as that is a reasonably safe case.  GCC also
3263       // doesn't emit a warning for that case.
3264       CoveredArgs.set(argIndex);
3265       const Expr *Arg = getDataArg(argIndex);
3266       if (!Arg)
3267         return false;
3268 
3269       QualType T = Arg->getType();
3270 
3271       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
3272       assert(AT.isValid());
3273 
3274       if (!AT.matchesType(S.Context, T)) {
3275         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
3276                                << k << AT.getRepresentativeTypeName(S.Context)
3277                                << T << Arg->getSourceRange(),
3278                              getLocationOfByte(Amt.getStart()),
3279                              /*IsStringLocation*/true,
3280                              getSpecifierRange(startSpecifier, specifierLen));
3281         // Don't do any more checking.  We will just emit
3282         // spurious errors.
3283         return false;
3284       }
3285     }
3286   }
3287   return true;
3288 }
3289 
3290 void CheckPrintfHandler::HandleInvalidAmount(
3291                                       const analyze_printf::PrintfSpecifier &FS,
3292                                       const analyze_printf::OptionalAmount &Amt,
3293                                       unsigned type,
3294                                       const char *startSpecifier,
3295                                       unsigned specifierLen) {
3296   const analyze_printf::PrintfConversionSpecifier &CS =
3297     FS.getConversionSpecifier();
3298 
3299   FixItHint fixit =
3300     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3301       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
3302                                  Amt.getConstantLength()))
3303       : FixItHint();
3304 
3305   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
3306                          << type << CS.toString(),
3307                        getLocationOfByte(Amt.getStart()),
3308                        /*IsStringLocation*/true,
3309                        getSpecifierRange(startSpecifier, specifierLen),
3310                        fixit);
3311 }
3312 
3313 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
3314                                     const analyze_printf::OptionalFlag &flag,
3315                                     const char *startSpecifier,
3316                                     unsigned specifierLen) {
3317   // Warn about pointless flag with a fixit removal.
3318   const analyze_printf::PrintfConversionSpecifier &CS =
3319     FS.getConversionSpecifier();
3320   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
3321                          << flag.toString() << CS.toString(),
3322                        getLocationOfByte(flag.getPosition()),
3323                        /*IsStringLocation*/true,
3324                        getSpecifierRange(startSpecifier, specifierLen),
3325                        FixItHint::CreateRemoval(
3326                          getSpecifierRange(flag.getPosition(), 1)));
3327 }
3328 
3329 void CheckPrintfHandler::HandleIgnoredFlag(
3330                                 const analyze_printf::PrintfSpecifier &FS,
3331                                 const analyze_printf::OptionalFlag &ignoredFlag,
3332                                 const analyze_printf::OptionalFlag &flag,
3333                                 const char *startSpecifier,
3334                                 unsigned specifierLen) {
3335   // Warn about ignored flag with a fixit removal.
3336   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
3337                          << ignoredFlag.toString() << flag.toString(),
3338                        getLocationOfByte(ignoredFlag.getPosition()),
3339                        /*IsStringLocation*/true,
3340                        getSpecifierRange(startSpecifier, specifierLen),
3341                        FixItHint::CreateRemoval(
3342                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
3343 }
3344 
3345 // Determines if the specified is a C++ class or struct containing
3346 // a member with the specified name and kind (e.g. a CXXMethodDecl named
3347 // "c_str()").
3348 template<typename MemberKind>
3349 static llvm::SmallPtrSet<MemberKind*, 1>
3350 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
3351   const RecordType *RT = Ty->getAs<RecordType>();
3352   llvm::SmallPtrSet<MemberKind*, 1> Results;
3353 
3354   if (!RT)
3355     return Results;
3356   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
3357   if (!RD || !RD->getDefinition())
3358     return Results;
3359 
3360   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
3361                  Sema::LookupMemberName);
3362   R.suppressDiagnostics();
3363 
3364   // We just need to include all members of the right kind turned up by the
3365   // filter, at this point.
3366   if (S.LookupQualifiedName(R, RT->getDecl()))
3367     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
3368       NamedDecl *decl = (*I)->getUnderlyingDecl();
3369       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3370         Results.insert(FK);
3371     }
3372   return Results;
3373 }
3374 
3375 /// Check if we could call '.c_str()' on an object.
3376 ///
3377 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
3378 /// allow the call, or if it would be ambiguous).
3379 bool Sema::hasCStrMethod(const Expr *E) {
3380   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3381   MethodSet Results =
3382       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
3383   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3384        MI != ME; ++MI)
3385     if ((*MI)->getMinRequiredArguments() == 0)
3386       return true;
3387   return false;
3388 }
3389 
3390 // Check if a (w)string was passed when a (w)char* was needed, and offer a
3391 // better diagnostic if so. AT is assumed to be valid.
3392 // Returns true when a c_str() conversion method is found.
3393 bool CheckPrintfHandler::checkForCStrMembers(
3394     const analyze_printf::ArgType &AT, const Expr *E) {
3395   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3396 
3397   MethodSet Results =
3398       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
3399 
3400   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3401        MI != ME; ++MI) {
3402     const CXXMethodDecl *Method = *MI;
3403     if (Method->getMinRequiredArguments() == 0 &&
3404         AT.matchesType(S.Context, Method->getReturnType())) {
3405       // FIXME: Suggest parens if the expression needs them.
3406       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
3407       S.Diag(E->getLocStart(), diag::note_printf_c_str)
3408           << "c_str()"
3409           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
3410       return true;
3411     }
3412   }
3413 
3414   return false;
3415 }
3416 
3417 bool
3418 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
3419                                             &FS,
3420                                           const char *startSpecifier,
3421                                           unsigned specifierLen) {
3422 
3423   using namespace analyze_format_string;
3424   using namespace analyze_printf;
3425   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
3426 
3427   if (FS.consumesDataArgument()) {
3428     if (atFirstArg) {
3429         atFirstArg = false;
3430         usesPositionalArgs = FS.usesPositionalArg();
3431     }
3432     else if (usesPositionalArgs != FS.usesPositionalArg()) {
3433       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3434                                         startSpecifier, specifierLen);
3435       return false;
3436     }
3437   }
3438 
3439   // First check if the field width, precision, and conversion specifier
3440   // have matching data arguments.
3441   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
3442                     startSpecifier, specifierLen)) {
3443     return false;
3444   }
3445 
3446   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
3447                     startSpecifier, specifierLen)) {
3448     return false;
3449   }
3450 
3451   if (!CS.consumesDataArgument()) {
3452     // FIXME: Technically specifying a precision or field width here
3453     // makes no sense.  Worth issuing a warning at some point.
3454     return true;
3455   }
3456 
3457   // Consume the argument.
3458   unsigned argIndex = FS.getArgIndex();
3459   if (argIndex < NumDataArgs) {
3460     // The check to see if the argIndex is valid will come later.
3461     // We set the bit here because we may exit early from this
3462     // function if we encounter some other error.
3463     CoveredArgs.set(argIndex);
3464   }
3465 
3466   // FreeBSD kernel extensions.
3467   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
3468       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
3469     // We need at least two arguments.
3470     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3471       return false;
3472 
3473     // Claim the second argument.
3474     CoveredArgs.set(argIndex + 1);
3475 
3476     // Type check the first argument (int for %b, pointer for %D)
3477     const Expr *Ex = getDataArg(argIndex);
3478     const analyze_printf::ArgType &AT =
3479       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
3480         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3481     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
3482       EmitFormatDiagnostic(
3483         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3484         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3485         << false << Ex->getSourceRange(),
3486         Ex->getLocStart(), /*IsStringLocation*/false,
3487         getSpecifierRange(startSpecifier, specifierLen));
3488 
3489     // Type check the second argument (char * for both %b and %D)
3490     Ex = getDataArg(argIndex + 1);
3491     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3492     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3493       EmitFormatDiagnostic(
3494         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3495         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3496         << false << Ex->getSourceRange(),
3497         Ex->getLocStart(), /*IsStringLocation*/false,
3498         getSpecifierRange(startSpecifier, specifierLen));
3499 
3500      return true;
3501   }
3502 
3503   // Check for using an Objective-C specific conversion specifier
3504   // in a non-ObjC literal.
3505   if (!ObjCContext && CS.isObjCArg()) {
3506     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3507                                                   specifierLen);
3508   }
3509 
3510   // Check for invalid use of field width
3511   if (!FS.hasValidFieldWidth()) {
3512     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
3513         startSpecifier, specifierLen);
3514   }
3515 
3516   // Check for invalid use of precision
3517   if (!FS.hasValidPrecision()) {
3518     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
3519         startSpecifier, specifierLen);
3520   }
3521 
3522   // Check each flag does not conflict with any other component.
3523   if (!FS.hasValidThousandsGroupingPrefix())
3524     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
3525   if (!FS.hasValidLeadingZeros())
3526     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3527   if (!FS.hasValidPlusPrefix())
3528     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
3529   if (!FS.hasValidSpacePrefix())
3530     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3531   if (!FS.hasValidAlternativeForm())
3532     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3533   if (!FS.hasValidLeftJustified())
3534     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3535 
3536   // Check that flags are not ignored by another flag
3537   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3538     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3539         startSpecifier, specifierLen);
3540   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3541     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3542             startSpecifier, specifierLen);
3543 
3544   // Check the length modifier is valid with the given conversion specifier.
3545   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3546     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3547                                 diag::warn_format_nonsensical_length);
3548   else if (!FS.hasStandardLengthModifier())
3549     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3550   else if (!FS.hasStandardLengthConversionCombination())
3551     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3552                                 diag::warn_format_non_standard_conversion_spec);
3553 
3554   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3555     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3556 
3557   // The remaining checks depend on the data arguments.
3558   if (HasVAListArg)
3559     return true;
3560 
3561   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3562     return false;
3563 
3564   const Expr *Arg = getDataArg(argIndex);
3565   if (!Arg)
3566     return true;
3567 
3568   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3569 }
3570 
3571 static bool requiresParensToAddCast(const Expr *E) {
3572   // FIXME: We should have a general way to reason about operator
3573   // precedence and whether parens are actually needed here.
3574   // Take care of a few common cases where they aren't.
3575   const Expr *Inside = E->IgnoreImpCasts();
3576   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3577     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3578 
3579   switch (Inside->getStmtClass()) {
3580   case Stmt::ArraySubscriptExprClass:
3581   case Stmt::CallExprClass:
3582   case Stmt::CharacterLiteralClass:
3583   case Stmt::CXXBoolLiteralExprClass:
3584   case Stmt::DeclRefExprClass:
3585   case Stmt::FloatingLiteralClass:
3586   case Stmt::IntegerLiteralClass:
3587   case Stmt::MemberExprClass:
3588   case Stmt::ObjCArrayLiteralClass:
3589   case Stmt::ObjCBoolLiteralExprClass:
3590   case Stmt::ObjCBoxedExprClass:
3591   case Stmt::ObjCDictionaryLiteralClass:
3592   case Stmt::ObjCEncodeExprClass:
3593   case Stmt::ObjCIvarRefExprClass:
3594   case Stmt::ObjCMessageExprClass:
3595   case Stmt::ObjCPropertyRefExprClass:
3596   case Stmt::ObjCStringLiteralClass:
3597   case Stmt::ObjCSubscriptRefExprClass:
3598   case Stmt::ParenExprClass:
3599   case Stmt::StringLiteralClass:
3600   case Stmt::UnaryOperatorClass:
3601     return false;
3602   default:
3603     return true;
3604   }
3605 }
3606 
3607 static std::pair<QualType, StringRef>
3608 shouldNotPrintDirectly(const ASTContext &Context,
3609                        QualType IntendedTy,
3610                        const Expr *E) {
3611   // Use a 'while' to peel off layers of typedefs.
3612   QualType TyTy = IntendedTy;
3613   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3614     StringRef Name = UserTy->getDecl()->getName();
3615     QualType CastTy = llvm::StringSwitch<QualType>(Name)
3616       .Case("NSInteger", Context.LongTy)
3617       .Case("NSUInteger", Context.UnsignedLongTy)
3618       .Case("SInt32", Context.IntTy)
3619       .Case("UInt32", Context.UnsignedIntTy)
3620       .Default(QualType());
3621 
3622     if (!CastTy.isNull())
3623       return std::make_pair(CastTy, Name);
3624 
3625     TyTy = UserTy->desugar();
3626   }
3627 
3628   // Strip parens if necessary.
3629   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
3630     return shouldNotPrintDirectly(Context,
3631                                   PE->getSubExpr()->getType(),
3632                                   PE->getSubExpr());
3633 
3634   // If this is a conditional expression, then its result type is constructed
3635   // via usual arithmetic conversions and thus there might be no necessary
3636   // typedef sugar there.  Recurse to operands to check for NSInteger &
3637   // Co. usage condition.
3638   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3639     QualType TrueTy, FalseTy;
3640     StringRef TrueName, FalseName;
3641 
3642     std::tie(TrueTy, TrueName) =
3643       shouldNotPrintDirectly(Context,
3644                              CO->getTrueExpr()->getType(),
3645                              CO->getTrueExpr());
3646     std::tie(FalseTy, FalseName) =
3647       shouldNotPrintDirectly(Context,
3648                              CO->getFalseExpr()->getType(),
3649                              CO->getFalseExpr());
3650 
3651     if (TrueTy == FalseTy)
3652       return std::make_pair(TrueTy, TrueName);
3653     else if (TrueTy.isNull())
3654       return std::make_pair(FalseTy, FalseName);
3655     else if (FalseTy.isNull())
3656       return std::make_pair(TrueTy, TrueName);
3657   }
3658 
3659   return std::make_pair(QualType(), StringRef());
3660 }
3661 
3662 bool
3663 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3664                                     const char *StartSpecifier,
3665                                     unsigned SpecifierLen,
3666                                     const Expr *E) {
3667   using namespace analyze_format_string;
3668   using namespace analyze_printf;
3669   // Now type check the data expression that matches the
3670   // format specifier.
3671   const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3672                                                     ObjCContext);
3673   if (!AT.isValid())
3674     return true;
3675 
3676   QualType ExprTy = E->getType();
3677   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3678     ExprTy = TET->getUnderlyingExpr()->getType();
3679   }
3680 
3681   if (AT.matchesType(S.Context, ExprTy))
3682     return true;
3683 
3684   // Look through argument promotions for our error message's reported type.
3685   // This includes the integral and floating promotions, but excludes array
3686   // and function pointer decay; seeing that an argument intended to be a
3687   // string has type 'char [6]' is probably more confusing than 'char *'.
3688   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3689     if (ICE->getCastKind() == CK_IntegralCast ||
3690         ICE->getCastKind() == CK_FloatingCast) {
3691       E = ICE->getSubExpr();
3692       ExprTy = E->getType();
3693 
3694       // Check if we didn't match because of an implicit cast from a 'char'
3695       // or 'short' to an 'int'.  This is done because printf is a varargs
3696       // function.
3697       if (ICE->getType() == S.Context.IntTy ||
3698           ICE->getType() == S.Context.UnsignedIntTy) {
3699         // All further checking is done on the subexpression.
3700         if (AT.matchesType(S.Context, ExprTy))
3701           return true;
3702       }
3703     }
3704   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3705     // Special case for 'a', which has type 'int' in C.
3706     // Note, however, that we do /not/ want to treat multibyte constants like
3707     // 'MooV' as characters! This form is deprecated but still exists.
3708     if (ExprTy == S.Context.IntTy)
3709       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3710         ExprTy = S.Context.CharTy;
3711   }
3712 
3713   // Look through enums to their underlying type.
3714   bool IsEnum = false;
3715   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
3716     ExprTy = EnumTy->getDecl()->getIntegerType();
3717     IsEnum = true;
3718   }
3719 
3720   // %C in an Objective-C context prints a unichar, not a wchar_t.
3721   // If the argument is an integer of some kind, believe the %C and suggest
3722   // a cast instead of changing the conversion specifier.
3723   QualType IntendedTy = ExprTy;
3724   if (ObjCContext &&
3725       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3726     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3727         !ExprTy->isCharType()) {
3728       // 'unichar' is defined as a typedef of unsigned short, but we should
3729       // prefer using the typedef if it is visible.
3730       IntendedTy = S.Context.UnsignedShortTy;
3731 
3732       // While we are here, check if the value is an IntegerLiteral that happens
3733       // to be within the valid range.
3734       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3735         const llvm::APInt &V = IL->getValue();
3736         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3737           return true;
3738       }
3739 
3740       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3741                           Sema::LookupOrdinaryName);
3742       if (S.LookupName(Result, S.getCurScope())) {
3743         NamedDecl *ND = Result.getFoundDecl();
3744         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3745           if (TD->getUnderlyingType() == IntendedTy)
3746             IntendedTy = S.Context.getTypedefType(TD);
3747       }
3748     }
3749   }
3750 
3751   // Special-case some of Darwin's platform-independence types by suggesting
3752   // casts to primitive types that are known to be large enough.
3753   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
3754   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
3755     QualType CastTy;
3756     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
3757     if (!CastTy.isNull()) {
3758       IntendedTy = CastTy;
3759       ShouldNotPrintDirectly = true;
3760     }
3761   }
3762 
3763   // We may be able to offer a FixItHint if it is a supported type.
3764   PrintfSpecifier fixedFS = FS;
3765   bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
3766                                  S.Context, ObjCContext);
3767 
3768   if (success) {
3769     // Get the fix string from the fixed format specifier
3770     SmallString<16> buf;
3771     llvm::raw_svector_ostream os(buf);
3772     fixedFS.toString(os);
3773 
3774     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3775 
3776     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
3777       // In this case, the specifier is wrong and should be changed to match
3778       // the argument.
3779       EmitFormatDiagnostic(
3780         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3781           << AT.getRepresentativeTypeName(S.Context) << IntendedTy << IsEnum
3782           << E->getSourceRange(),
3783         E->getLocStart(),
3784         /*IsStringLocation*/false,
3785         SpecRange,
3786         FixItHint::CreateReplacement(SpecRange, os.str()));
3787 
3788     } else {
3789       // The canonical type for formatting this value is different from the
3790       // actual type of the expression. (This occurs, for example, with Darwin's
3791       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3792       // should be printed as 'long' for 64-bit compatibility.)
3793       // Rather than emitting a normal format/argument mismatch, we want to
3794       // add a cast to the recommended type (and correct the format string
3795       // if necessary).
3796       SmallString<16> CastBuf;
3797       llvm::raw_svector_ostream CastFix(CastBuf);
3798       CastFix << "(";
3799       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3800       CastFix << ")";
3801 
3802       SmallVector<FixItHint,4> Hints;
3803       if (!AT.matchesType(S.Context, IntendedTy))
3804         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3805 
3806       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3807         // If there's already a cast present, just replace it.
3808         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3809         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3810 
3811       } else if (!requiresParensToAddCast(E)) {
3812         // If the expression has high enough precedence,
3813         // just write the C-style cast.
3814         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3815                                                    CastFix.str()));
3816       } else {
3817         // Otherwise, add parens around the expression as well as the cast.
3818         CastFix << "(";
3819         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3820                                                    CastFix.str()));
3821 
3822         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
3823         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3824       }
3825 
3826       if (ShouldNotPrintDirectly) {
3827         // The expression has a type that should not be printed directly.
3828         // We extract the name from the typedef because we don't want to show
3829         // the underlying type in the diagnostic.
3830         StringRef Name;
3831         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
3832           Name = TypedefTy->getDecl()->getName();
3833         else
3834           Name = CastTyName;
3835         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3836                                << Name << IntendedTy << IsEnum
3837                                << E->getSourceRange(),
3838                              E->getLocStart(), /*IsStringLocation=*/false,
3839                              SpecRange, Hints);
3840       } else {
3841         // In this case, the expression could be printed using a different
3842         // specifier, but we've decided that the specifier is probably correct
3843         // and we should cast instead. Just use the normal warning message.
3844         EmitFormatDiagnostic(
3845           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3846             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
3847             << E->getSourceRange(),
3848           E->getLocStart(), /*IsStringLocation*/false,
3849           SpecRange, Hints);
3850       }
3851     }
3852   } else {
3853     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3854                                                    SpecifierLen);
3855     // Since the warning for passing non-POD types to variadic functions
3856     // was deferred until now, we emit a warning for non-POD
3857     // arguments here.
3858     switch (S.isValidVarArgType(ExprTy)) {
3859     case Sema::VAK_Valid:
3860     case Sema::VAK_ValidInCXX11:
3861       EmitFormatDiagnostic(
3862         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3863           << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
3864           << CSR
3865           << E->getSourceRange(),
3866         E->getLocStart(), /*IsStringLocation*/false, CSR);
3867       break;
3868 
3869     case Sema::VAK_Undefined:
3870     case Sema::VAK_MSVCUndefined:
3871       EmitFormatDiagnostic(
3872         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
3873           << S.getLangOpts().CPlusPlus11
3874           << ExprTy
3875           << CallType
3876           << AT.getRepresentativeTypeName(S.Context)
3877           << CSR
3878           << E->getSourceRange(),
3879         E->getLocStart(), /*IsStringLocation*/false, CSR);
3880       checkForCStrMembers(AT, E);
3881       break;
3882 
3883     case Sema::VAK_Invalid:
3884       if (ExprTy->isObjCObjectType())
3885         EmitFormatDiagnostic(
3886           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3887             << S.getLangOpts().CPlusPlus11
3888             << ExprTy
3889             << CallType
3890             << AT.getRepresentativeTypeName(S.Context)
3891             << CSR
3892             << E->getSourceRange(),
3893           E->getLocStart(), /*IsStringLocation*/false, CSR);
3894       else
3895         // FIXME: If this is an initializer list, suggest removing the braces
3896         // or inserting a cast to the target type.
3897         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3898           << isa<InitListExpr>(E) << ExprTy << CallType
3899           << AT.getRepresentativeTypeName(S.Context)
3900           << E->getSourceRange();
3901       break;
3902     }
3903 
3904     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3905            "format string specifier index out of range");
3906     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
3907   }
3908 
3909   return true;
3910 }
3911 
3912 //===--- CHECK: Scanf format string checking ------------------------------===//
3913 
3914 namespace {
3915 class CheckScanfHandler : public CheckFormatHandler {
3916 public:
3917   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3918                     const Expr *origFormatExpr, unsigned firstDataArg,
3919                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
3920                     ArrayRef<const Expr *> Args,
3921                     unsigned formatIdx, bool inFunctionCall,
3922                     Sema::VariadicCallType CallType,
3923                     llvm::SmallBitVector &CheckedVarArgs)
3924     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3925                          numDataArgs, beg, hasVAListArg,
3926                          Args, formatIdx, inFunctionCall, CallType,
3927                          CheckedVarArgs)
3928   {}
3929 
3930   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3931                             const char *startSpecifier,
3932                             unsigned specifierLen) override;
3933 
3934   bool HandleInvalidScanfConversionSpecifier(
3935           const analyze_scanf::ScanfSpecifier &FS,
3936           const char *startSpecifier,
3937           unsigned specifierLen) override;
3938 
3939   void HandleIncompleteScanList(const char *start, const char *end) override;
3940 };
3941 }
3942 
3943 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3944                                                  const char *end) {
3945   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3946                        getLocationOfByte(end), /*IsStringLocation*/true,
3947                        getSpecifierRange(start, end - start));
3948 }
3949 
3950 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3951                                         const analyze_scanf::ScanfSpecifier &FS,
3952                                         const char *startSpecifier,
3953                                         unsigned specifierLen) {
3954 
3955   const analyze_scanf::ScanfConversionSpecifier &CS =
3956     FS.getConversionSpecifier();
3957 
3958   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3959                                           getLocationOfByte(CS.getStart()),
3960                                           startSpecifier, specifierLen,
3961                                           CS.getStart(), CS.getLength());
3962 }
3963 
3964 bool CheckScanfHandler::HandleScanfSpecifier(
3965                                        const analyze_scanf::ScanfSpecifier &FS,
3966                                        const char *startSpecifier,
3967                                        unsigned specifierLen) {
3968 
3969   using namespace analyze_scanf;
3970   using namespace analyze_format_string;
3971 
3972   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
3973 
3974   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
3975   // be used to decide if we are using positional arguments consistently.
3976   if (FS.consumesDataArgument()) {
3977     if (atFirstArg) {
3978       atFirstArg = false;
3979       usesPositionalArgs = FS.usesPositionalArg();
3980     }
3981     else if (usesPositionalArgs != FS.usesPositionalArg()) {
3982       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3983                                         startSpecifier, specifierLen);
3984       return false;
3985     }
3986   }
3987 
3988   // Check if the field with is non-zero.
3989   const OptionalAmount &Amt = FS.getFieldWidth();
3990   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3991     if (Amt.getConstantAmount() == 0) {
3992       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3993                                                    Amt.getConstantLength());
3994       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3995                            getLocationOfByte(Amt.getStart()),
3996                            /*IsStringLocation*/true, R,
3997                            FixItHint::CreateRemoval(R));
3998     }
3999   }
4000 
4001   if (!FS.consumesDataArgument()) {
4002     // FIXME: Technically specifying a precision or field width here
4003     // makes no sense.  Worth issuing a warning at some point.
4004     return true;
4005   }
4006 
4007   // Consume the argument.
4008   unsigned argIndex = FS.getArgIndex();
4009   if (argIndex < NumDataArgs) {
4010       // The check to see if the argIndex is valid will come later.
4011       // We set the bit here because we may exit early from this
4012       // function if we encounter some other error.
4013     CoveredArgs.set(argIndex);
4014   }
4015 
4016   // Check the length modifier is valid with the given conversion specifier.
4017   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
4018     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4019                                 diag::warn_format_nonsensical_length);
4020   else if (!FS.hasStandardLengthModifier())
4021     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
4022   else if (!FS.hasStandardLengthConversionCombination())
4023     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4024                                 diag::warn_format_non_standard_conversion_spec);
4025 
4026   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4027     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4028 
4029   // The remaining checks depend on the data arguments.
4030   if (HasVAListArg)
4031     return true;
4032 
4033   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
4034     return false;
4035 
4036   // Check that the argument type matches the format specifier.
4037   const Expr *Ex = getDataArg(argIndex);
4038   if (!Ex)
4039     return true;
4040 
4041   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
4042   if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
4043     ScanfSpecifier fixedFS = FS;
4044     bool success = fixedFS.fixType(Ex->getType(),
4045                                    Ex->IgnoreImpCasts()->getType(),
4046                                    S.getLangOpts(), S.Context);
4047 
4048     if (success) {
4049       // Get the fix string from the fixed format specifier.
4050       SmallString<128> buf;
4051       llvm::raw_svector_ostream os(buf);
4052       fixedFS.toString(os);
4053 
4054       EmitFormatDiagnostic(
4055         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4056           << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
4057           << Ex->getSourceRange(),
4058         Ex->getLocStart(),
4059         /*IsStringLocation*/false,
4060         getSpecifierRange(startSpecifier, specifierLen),
4061         FixItHint::CreateReplacement(
4062           getSpecifierRange(startSpecifier, specifierLen),
4063           os.str()));
4064     } else {
4065       EmitFormatDiagnostic(
4066         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4067           << AT.getRepresentativeTypeName(S.Context) << Ex->getType() << false
4068           << Ex->getSourceRange(),
4069         Ex->getLocStart(),
4070         /*IsStringLocation*/false,
4071         getSpecifierRange(startSpecifier, specifierLen));
4072     }
4073   }
4074 
4075   return true;
4076 }
4077 
4078 void Sema::CheckFormatString(const StringLiteral *FExpr,
4079                              const Expr *OrigFormatExpr,
4080                              ArrayRef<const Expr *> Args,
4081                              bool HasVAListArg, unsigned format_idx,
4082                              unsigned firstDataArg, FormatStringType Type,
4083                              bool inFunctionCall, VariadicCallType CallType,
4084                              llvm::SmallBitVector &CheckedVarArgs) {
4085 
4086   // CHECK: is the format string a wide literal?
4087   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
4088     CheckFormatHandler::EmitFormatDiagnostic(
4089       *this, inFunctionCall, Args[format_idx],
4090       PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
4091       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
4092     return;
4093   }
4094 
4095   // Str - The format string.  NOTE: this is NOT null-terminated!
4096   StringRef StrRef = FExpr->getString();
4097   const char *Str = StrRef.data();
4098   // Account for cases where the string literal is truncated in a declaration.
4099   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4100   assert(T && "String literal not of constant array type!");
4101   size_t TypeSize = T->getSize().getZExtValue();
4102   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4103   const unsigned numDataArgs = Args.size() - firstDataArg;
4104 
4105   // Emit a warning if the string literal is truncated and does not contain an
4106   // embedded null character.
4107   if (TypeSize <= StrRef.size() &&
4108       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
4109     CheckFormatHandler::EmitFormatDiagnostic(
4110         *this, inFunctionCall, Args[format_idx],
4111         PDiag(diag::warn_printf_format_string_not_null_terminated),
4112         FExpr->getLocStart(),
4113         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
4114     return;
4115   }
4116 
4117   // CHECK: empty format string?
4118   if (StrLen == 0 && numDataArgs > 0) {
4119     CheckFormatHandler::EmitFormatDiagnostic(
4120       *this, inFunctionCall, Args[format_idx],
4121       PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
4122       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
4123     return;
4124   }
4125 
4126   if (Type == FST_Printf || Type == FST_NSString ||
4127       Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
4128     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
4129                          numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
4130                          Str, HasVAListArg, Args, format_idx,
4131                          inFunctionCall, CallType, CheckedVarArgs);
4132 
4133     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
4134                                                   getLangOpts(),
4135                                                   Context.getTargetInfo(),
4136                                                   Type == FST_FreeBSDKPrintf))
4137       H.DoneProcessing();
4138   } else if (Type == FST_Scanf) {
4139     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
4140                         Str, HasVAListArg, Args, format_idx,
4141                         inFunctionCall, CallType, CheckedVarArgs);
4142 
4143     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
4144                                                  getLangOpts(),
4145                                                  Context.getTargetInfo()))
4146       H.DoneProcessing();
4147   } // TODO: handle other formats
4148 }
4149 
4150 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
4151   // Str - The format string.  NOTE: this is NOT null-terminated!
4152   StringRef StrRef = FExpr->getString();
4153   const char *Str = StrRef.data();
4154   // Account for cases where the string literal is truncated in a declaration.
4155   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
4156   assert(T && "String literal not of constant array type!");
4157   size_t TypeSize = T->getSize().getZExtValue();
4158   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
4159   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
4160                                                          getLangOpts(),
4161                                                          Context.getTargetInfo());
4162 }
4163 
4164 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
4165 
4166 // Returns the related absolute value function that is larger, of 0 if one
4167 // does not exist.
4168 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
4169   switch (AbsFunction) {
4170   default:
4171     return 0;
4172 
4173   case Builtin::BI__builtin_abs:
4174     return Builtin::BI__builtin_labs;
4175   case Builtin::BI__builtin_labs:
4176     return Builtin::BI__builtin_llabs;
4177   case Builtin::BI__builtin_llabs:
4178     return 0;
4179 
4180   case Builtin::BI__builtin_fabsf:
4181     return Builtin::BI__builtin_fabs;
4182   case Builtin::BI__builtin_fabs:
4183     return Builtin::BI__builtin_fabsl;
4184   case Builtin::BI__builtin_fabsl:
4185     return 0;
4186 
4187   case Builtin::BI__builtin_cabsf:
4188     return Builtin::BI__builtin_cabs;
4189   case Builtin::BI__builtin_cabs:
4190     return Builtin::BI__builtin_cabsl;
4191   case Builtin::BI__builtin_cabsl:
4192     return 0;
4193 
4194   case Builtin::BIabs:
4195     return Builtin::BIlabs;
4196   case Builtin::BIlabs:
4197     return Builtin::BIllabs;
4198   case Builtin::BIllabs:
4199     return 0;
4200 
4201   case Builtin::BIfabsf:
4202     return Builtin::BIfabs;
4203   case Builtin::BIfabs:
4204     return Builtin::BIfabsl;
4205   case Builtin::BIfabsl:
4206     return 0;
4207 
4208   case Builtin::BIcabsf:
4209    return Builtin::BIcabs;
4210   case Builtin::BIcabs:
4211     return Builtin::BIcabsl;
4212   case Builtin::BIcabsl:
4213     return 0;
4214   }
4215 }
4216 
4217 // Returns the argument type of the absolute value function.
4218 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
4219                                              unsigned AbsType) {
4220   if (AbsType == 0)
4221     return QualType();
4222 
4223   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
4224   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
4225   if (Error != ASTContext::GE_None)
4226     return QualType();
4227 
4228   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
4229   if (!FT)
4230     return QualType();
4231 
4232   if (FT->getNumParams() != 1)
4233     return QualType();
4234 
4235   return FT->getParamType(0);
4236 }
4237 
4238 // Returns the best absolute value function, or zero, based on type and
4239 // current absolute value function.
4240 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
4241                                    unsigned AbsFunctionKind) {
4242   unsigned BestKind = 0;
4243   uint64_t ArgSize = Context.getTypeSize(ArgType);
4244   for (unsigned Kind = AbsFunctionKind; Kind != 0;
4245        Kind = getLargerAbsoluteValueFunction(Kind)) {
4246     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
4247     if (Context.getTypeSize(ParamType) >= ArgSize) {
4248       if (BestKind == 0)
4249         BestKind = Kind;
4250       else if (Context.hasSameType(ParamType, ArgType)) {
4251         BestKind = Kind;
4252         break;
4253       }
4254     }
4255   }
4256   return BestKind;
4257 }
4258 
4259 enum AbsoluteValueKind {
4260   AVK_Integer,
4261   AVK_Floating,
4262   AVK_Complex
4263 };
4264 
4265 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
4266   if (T->isIntegralOrEnumerationType())
4267     return AVK_Integer;
4268   if (T->isRealFloatingType())
4269     return AVK_Floating;
4270   if (T->isAnyComplexType())
4271     return AVK_Complex;
4272 
4273   llvm_unreachable("Type not integer, floating, or complex");
4274 }
4275 
4276 // Changes the absolute value function to a different type.  Preserves whether
4277 // the function is a builtin.
4278 static unsigned changeAbsFunction(unsigned AbsKind,
4279                                   AbsoluteValueKind ValueKind) {
4280   switch (ValueKind) {
4281   case AVK_Integer:
4282     switch (AbsKind) {
4283     default:
4284       return 0;
4285     case Builtin::BI__builtin_fabsf:
4286     case Builtin::BI__builtin_fabs:
4287     case Builtin::BI__builtin_fabsl:
4288     case Builtin::BI__builtin_cabsf:
4289     case Builtin::BI__builtin_cabs:
4290     case Builtin::BI__builtin_cabsl:
4291       return Builtin::BI__builtin_abs;
4292     case Builtin::BIfabsf:
4293     case Builtin::BIfabs:
4294     case Builtin::BIfabsl:
4295     case Builtin::BIcabsf:
4296     case Builtin::BIcabs:
4297     case Builtin::BIcabsl:
4298       return Builtin::BIabs;
4299     }
4300   case AVK_Floating:
4301     switch (AbsKind) {
4302     default:
4303       return 0;
4304     case Builtin::BI__builtin_abs:
4305     case Builtin::BI__builtin_labs:
4306     case Builtin::BI__builtin_llabs:
4307     case Builtin::BI__builtin_cabsf:
4308     case Builtin::BI__builtin_cabs:
4309     case Builtin::BI__builtin_cabsl:
4310       return Builtin::BI__builtin_fabsf;
4311     case Builtin::BIabs:
4312     case Builtin::BIlabs:
4313     case Builtin::BIllabs:
4314     case Builtin::BIcabsf:
4315     case Builtin::BIcabs:
4316     case Builtin::BIcabsl:
4317       return Builtin::BIfabsf;
4318     }
4319   case AVK_Complex:
4320     switch (AbsKind) {
4321     default:
4322       return 0;
4323     case Builtin::BI__builtin_abs:
4324     case Builtin::BI__builtin_labs:
4325     case Builtin::BI__builtin_llabs:
4326     case Builtin::BI__builtin_fabsf:
4327     case Builtin::BI__builtin_fabs:
4328     case Builtin::BI__builtin_fabsl:
4329       return Builtin::BI__builtin_cabsf;
4330     case Builtin::BIabs:
4331     case Builtin::BIlabs:
4332     case Builtin::BIllabs:
4333     case Builtin::BIfabsf:
4334     case Builtin::BIfabs:
4335     case Builtin::BIfabsl:
4336       return Builtin::BIcabsf;
4337     }
4338   }
4339   llvm_unreachable("Unable to convert function");
4340 }
4341 
4342 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
4343   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
4344   if (!FnInfo)
4345     return 0;
4346 
4347   switch (FDecl->getBuiltinID()) {
4348   default:
4349     return 0;
4350   case Builtin::BI__builtin_abs:
4351   case Builtin::BI__builtin_fabs:
4352   case Builtin::BI__builtin_fabsf:
4353   case Builtin::BI__builtin_fabsl:
4354   case Builtin::BI__builtin_labs:
4355   case Builtin::BI__builtin_llabs:
4356   case Builtin::BI__builtin_cabs:
4357   case Builtin::BI__builtin_cabsf:
4358   case Builtin::BI__builtin_cabsl:
4359   case Builtin::BIabs:
4360   case Builtin::BIlabs:
4361   case Builtin::BIllabs:
4362   case Builtin::BIfabs:
4363   case Builtin::BIfabsf:
4364   case Builtin::BIfabsl:
4365   case Builtin::BIcabs:
4366   case Builtin::BIcabsf:
4367   case Builtin::BIcabsl:
4368     return FDecl->getBuiltinID();
4369   }
4370   llvm_unreachable("Unknown Builtin type");
4371 }
4372 
4373 // If the replacement is valid, emit a note with replacement function.
4374 // Additionally, suggest including the proper header if not already included.
4375 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
4376                             unsigned AbsKind, QualType ArgType) {
4377   bool EmitHeaderHint = true;
4378   const char *HeaderName = nullptr;
4379   const char *FunctionName = nullptr;
4380   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
4381     FunctionName = "std::abs";
4382     if (ArgType->isIntegralOrEnumerationType()) {
4383       HeaderName = "cstdlib";
4384     } else if (ArgType->isRealFloatingType()) {
4385       HeaderName = "cmath";
4386     } else {
4387       llvm_unreachable("Invalid Type");
4388     }
4389 
4390     // Lookup all std::abs
4391     if (NamespaceDecl *Std = S.getStdNamespace()) {
4392       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
4393       R.suppressDiagnostics();
4394       S.LookupQualifiedName(R, Std);
4395 
4396       for (const auto *I : R) {
4397         const FunctionDecl *FDecl = nullptr;
4398         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
4399           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
4400         } else {
4401           FDecl = dyn_cast<FunctionDecl>(I);
4402         }
4403         if (!FDecl)
4404           continue;
4405 
4406         // Found std::abs(), check that they are the right ones.
4407         if (FDecl->getNumParams() != 1)
4408           continue;
4409 
4410         // Check that the parameter type can handle the argument.
4411         QualType ParamType = FDecl->getParamDecl(0)->getType();
4412         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
4413             S.Context.getTypeSize(ArgType) <=
4414                 S.Context.getTypeSize(ParamType)) {
4415           // Found a function, don't need the header hint.
4416           EmitHeaderHint = false;
4417           break;
4418         }
4419       }
4420     }
4421   } else {
4422     FunctionName = S.Context.BuiltinInfo.GetName(AbsKind);
4423     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
4424 
4425     if (HeaderName) {
4426       DeclarationName DN(&S.Context.Idents.get(FunctionName));
4427       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
4428       R.suppressDiagnostics();
4429       S.LookupName(R, S.getCurScope());
4430 
4431       if (R.isSingleResult()) {
4432         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
4433         if (FD && FD->getBuiltinID() == AbsKind) {
4434           EmitHeaderHint = false;
4435         } else {
4436           return;
4437         }
4438       } else if (!R.empty()) {
4439         return;
4440       }
4441     }
4442   }
4443 
4444   S.Diag(Loc, diag::note_replace_abs_function)
4445       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
4446 
4447   if (!HeaderName)
4448     return;
4449 
4450   if (!EmitHeaderHint)
4451     return;
4452 
4453   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4454                                                     << FunctionName;
4455 }
4456 
4457 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
4458   if (!FDecl)
4459     return false;
4460 
4461   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
4462     return false;
4463 
4464   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
4465 
4466   while (ND && ND->isInlineNamespace()) {
4467     ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
4468   }
4469 
4470   if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
4471     return false;
4472 
4473   if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
4474     return false;
4475 
4476   return true;
4477 }
4478 
4479 // Warn when using the wrong abs() function.
4480 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
4481                                       const FunctionDecl *FDecl,
4482                                       IdentifierInfo *FnInfo) {
4483   if (Call->getNumArgs() != 1)
4484     return;
4485 
4486   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
4487   bool IsStdAbs = IsFunctionStdAbs(FDecl);
4488   if (AbsKind == 0 && !IsStdAbs)
4489     return;
4490 
4491   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
4492   QualType ParamType = Call->getArg(0)->getType();
4493 
4494   // Unsigned types cannot be negative.  Suggest removing the absolute value
4495   // function call.
4496   if (ArgType->isUnsignedIntegerType()) {
4497     const char *FunctionName =
4498         IsStdAbs ? "std::abs" : Context.BuiltinInfo.GetName(AbsKind);
4499     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4500     Diag(Call->getExprLoc(), diag::note_remove_abs)
4501         << FunctionName
4502         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
4503     return;
4504   }
4505 
4506   // std::abs has overloads which prevent most of the absolute value problems
4507   // from occurring.
4508   if (IsStdAbs)
4509     return;
4510 
4511   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
4512   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
4513 
4514   // The argument and parameter are the same kind.  Check if they are the right
4515   // size.
4516   if (ArgValueKind == ParamValueKind) {
4517     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
4518       return;
4519 
4520     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
4521     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
4522         << FDecl << ArgType << ParamType;
4523 
4524     if (NewAbsKind == 0)
4525       return;
4526 
4527     emitReplacement(*this, Call->getExprLoc(),
4528                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
4529     return;
4530   }
4531 
4532   // ArgValueKind != ParamValueKind
4533   // The wrong type of absolute value function was used.  Attempt to find the
4534   // proper one.
4535   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
4536   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
4537   if (NewAbsKind == 0)
4538     return;
4539 
4540   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
4541       << FDecl << ParamValueKind << ArgValueKind;
4542 
4543   emitReplacement(*this, Call->getExprLoc(),
4544                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
4545   return;
4546 }
4547 
4548 //===--- CHECK: Standard memory functions ---------------------------------===//
4549 
4550 /// \brief Takes the expression passed to the size_t parameter of functions
4551 /// such as memcmp, strncat, etc and warns if it's a comparison.
4552 ///
4553 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
4554 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
4555                                            IdentifierInfo *FnName,
4556                                            SourceLocation FnLoc,
4557                                            SourceLocation RParenLoc) {
4558   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
4559   if (!Size)
4560     return false;
4561 
4562   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
4563   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
4564     return false;
4565 
4566   SourceRange SizeRange = Size->getSourceRange();
4567   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
4568       << SizeRange << FnName;
4569   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
4570       << FnName << FixItHint::CreateInsertion(
4571                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
4572       << FixItHint::CreateRemoval(RParenLoc);
4573   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
4574       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
4575       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
4576                                     ")");
4577 
4578   return true;
4579 }
4580 
4581 /// \brief Determine whether the given type is or contains a dynamic class type
4582 /// (e.g., whether it has a vtable).
4583 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
4584                                                      bool &IsContained) {
4585   // Look through array types while ignoring qualifiers.
4586   const Type *Ty = T->getBaseElementTypeUnsafe();
4587   IsContained = false;
4588 
4589   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
4590   RD = RD ? RD->getDefinition() : nullptr;
4591   if (!RD)
4592     return nullptr;
4593 
4594   if (RD->isDynamicClass())
4595     return RD;
4596 
4597   // Check all the fields.  If any bases were dynamic, the class is dynamic.
4598   // It's impossible for a class to transitively contain itself by value, so
4599   // infinite recursion is impossible.
4600   for (auto *FD : RD->fields()) {
4601     bool SubContained;
4602     if (const CXXRecordDecl *ContainedRD =
4603             getContainedDynamicClass(FD->getType(), SubContained)) {
4604       IsContained = true;
4605       return ContainedRD;
4606     }
4607   }
4608 
4609   return nullptr;
4610 }
4611 
4612 /// \brief If E is a sizeof expression, returns its argument expression,
4613 /// otherwise returns NULL.
4614 static const Expr *getSizeOfExprArg(const Expr* E) {
4615   if (const UnaryExprOrTypeTraitExpr *SizeOf =
4616       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4617     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
4618       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
4619 
4620   return nullptr;
4621 }
4622 
4623 /// \brief If E is a sizeof expression, returns its argument type.
4624 static QualType getSizeOfArgType(const Expr* E) {
4625   if (const UnaryExprOrTypeTraitExpr *SizeOf =
4626       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
4627     if (SizeOf->getKind() == clang::UETT_SizeOf)
4628       return SizeOf->getTypeOfArgument();
4629 
4630   return QualType();
4631 }
4632 
4633 /// \brief Check for dangerous or invalid arguments to memset().
4634 ///
4635 /// This issues warnings on known problematic, dangerous or unspecified
4636 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
4637 /// function calls.
4638 ///
4639 /// \param Call The call expression to diagnose.
4640 void Sema::CheckMemaccessArguments(const CallExpr *Call,
4641                                    unsigned BId,
4642                                    IdentifierInfo *FnName) {
4643   assert(BId != 0);
4644 
4645   // It is possible to have a non-standard definition of memset.  Validate
4646   // we have enough arguments, and if not, abort further checking.
4647   unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
4648   if (Call->getNumArgs() < ExpectedNumArgs)
4649     return;
4650 
4651   unsigned LastArg = (BId == Builtin::BImemset ||
4652                       BId == Builtin::BIstrndup ? 1 : 2);
4653   unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
4654   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
4655 
4656   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
4657                                      Call->getLocStart(), Call->getRParenLoc()))
4658     return;
4659 
4660   // We have special checking when the length is a sizeof expression.
4661   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
4662   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
4663   llvm::FoldingSetNodeID SizeOfArgID;
4664 
4665   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
4666     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
4667     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
4668 
4669     QualType DestTy = Dest->getType();
4670     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
4671       QualType PointeeTy = DestPtrTy->getPointeeType();
4672 
4673       // Never warn about void type pointers. This can be used to suppress
4674       // false positives.
4675       if (PointeeTy->isVoidType())
4676         continue;
4677 
4678       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
4679       // actually comparing the expressions for equality. Because computing the
4680       // expression IDs can be expensive, we only do this if the diagnostic is
4681       // enabled.
4682       if (SizeOfArg &&
4683           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
4684                            SizeOfArg->getExprLoc())) {
4685         // We only compute IDs for expressions if the warning is enabled, and
4686         // cache the sizeof arg's ID.
4687         if (SizeOfArgID == llvm::FoldingSetNodeID())
4688           SizeOfArg->Profile(SizeOfArgID, Context, true);
4689         llvm::FoldingSetNodeID DestID;
4690         Dest->Profile(DestID, Context, true);
4691         if (DestID == SizeOfArgID) {
4692           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
4693           //       over sizeof(src) as well.
4694           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
4695           StringRef ReadableName = FnName->getName();
4696 
4697           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
4698             if (UnaryOp->getOpcode() == UO_AddrOf)
4699               ActionIdx = 1; // If its an address-of operator, just remove it.
4700           if (!PointeeTy->isIncompleteType() &&
4701               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
4702             ActionIdx = 2; // If the pointee's size is sizeof(char),
4703                            // suggest an explicit length.
4704 
4705           // If the function is defined as a builtin macro, do not show macro
4706           // expansion.
4707           SourceLocation SL = SizeOfArg->getExprLoc();
4708           SourceRange DSR = Dest->getSourceRange();
4709           SourceRange SSR = SizeOfArg->getSourceRange();
4710           SourceManager &SM = getSourceManager();
4711 
4712           if (SM.isMacroArgExpansion(SL)) {
4713             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
4714             SL = SM.getSpellingLoc(SL);
4715             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
4716                              SM.getSpellingLoc(DSR.getEnd()));
4717             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
4718                              SM.getSpellingLoc(SSR.getEnd()));
4719           }
4720 
4721           DiagRuntimeBehavior(SL, SizeOfArg,
4722                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
4723                                 << ReadableName
4724                                 << PointeeTy
4725                                 << DestTy
4726                                 << DSR
4727                                 << SSR);
4728           DiagRuntimeBehavior(SL, SizeOfArg,
4729                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
4730                                 << ActionIdx
4731                                 << SSR);
4732 
4733           break;
4734         }
4735       }
4736 
4737       // Also check for cases where the sizeof argument is the exact same
4738       // type as the memory argument, and where it points to a user-defined
4739       // record type.
4740       if (SizeOfArgTy != QualType()) {
4741         if (PointeeTy->isRecordType() &&
4742             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
4743           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
4744                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
4745                                 << FnName << SizeOfArgTy << ArgIdx
4746                                 << PointeeTy << Dest->getSourceRange()
4747                                 << LenExpr->getSourceRange());
4748           break;
4749         }
4750       }
4751 
4752       // Always complain about dynamic classes.
4753       bool IsContained;
4754       if (const CXXRecordDecl *ContainedRD =
4755               getContainedDynamicClass(PointeeTy, IsContained)) {
4756 
4757         unsigned OperationType = 0;
4758         // "overwritten" if we're warning about the destination for any call
4759         // but memcmp; otherwise a verb appropriate to the call.
4760         if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
4761           if (BId == Builtin::BImemcpy)
4762             OperationType = 1;
4763           else if(BId == Builtin::BImemmove)
4764             OperationType = 2;
4765           else if (BId == Builtin::BImemcmp)
4766             OperationType = 3;
4767         }
4768 
4769         DiagRuntimeBehavior(
4770           Dest->getExprLoc(), Dest,
4771           PDiag(diag::warn_dyn_class_memaccess)
4772             << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
4773             << FnName << IsContained << ContainedRD << OperationType
4774             << Call->getCallee()->getSourceRange());
4775       } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
4776                BId != Builtin::BImemset)
4777         DiagRuntimeBehavior(
4778           Dest->getExprLoc(), Dest,
4779           PDiag(diag::warn_arc_object_memaccess)
4780             << ArgIdx << FnName << PointeeTy
4781             << Call->getCallee()->getSourceRange());
4782       else
4783         continue;
4784 
4785       DiagRuntimeBehavior(
4786         Dest->getExprLoc(), Dest,
4787         PDiag(diag::note_bad_memaccess_silence)
4788           << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
4789       break;
4790     }
4791   }
4792 }
4793 
4794 // A little helper routine: ignore addition and subtraction of integer literals.
4795 // This intentionally does not ignore all integer constant expressions because
4796 // we don't want to remove sizeof().
4797 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
4798   Ex = Ex->IgnoreParenCasts();
4799 
4800   for (;;) {
4801     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
4802     if (!BO || !BO->isAdditiveOp())
4803       break;
4804 
4805     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
4806     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
4807 
4808     if (isa<IntegerLiteral>(RHS))
4809       Ex = LHS;
4810     else if (isa<IntegerLiteral>(LHS))
4811       Ex = RHS;
4812     else
4813       break;
4814   }
4815 
4816   return Ex;
4817 }
4818 
4819 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
4820                                                       ASTContext &Context) {
4821   // Only handle constant-sized or VLAs, but not flexible members.
4822   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
4823     // Only issue the FIXIT for arrays of size > 1.
4824     if (CAT->getSize().getSExtValue() <= 1)
4825       return false;
4826   } else if (!Ty->isVariableArrayType()) {
4827     return false;
4828   }
4829   return true;
4830 }
4831 
4832 // Warn if the user has made the 'size' argument to strlcpy or strlcat
4833 // be the size of the source, instead of the destination.
4834 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
4835                                     IdentifierInfo *FnName) {
4836 
4837   // Don't crash if the user has the wrong number of arguments
4838   unsigned NumArgs = Call->getNumArgs();
4839   if ((NumArgs != 3) && (NumArgs != 4))
4840     return;
4841 
4842   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
4843   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
4844   const Expr *CompareWithSrc = nullptr;
4845 
4846   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
4847                                      Call->getLocStart(), Call->getRParenLoc()))
4848     return;
4849 
4850   // Look for 'strlcpy(dst, x, sizeof(x))'
4851   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
4852     CompareWithSrc = Ex;
4853   else {
4854     // Look for 'strlcpy(dst, x, strlen(x))'
4855     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
4856       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
4857           SizeCall->getNumArgs() == 1)
4858         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
4859     }
4860   }
4861 
4862   if (!CompareWithSrc)
4863     return;
4864 
4865   // Determine if the argument to sizeof/strlen is equal to the source
4866   // argument.  In principle there's all kinds of things you could do
4867   // here, for instance creating an == expression and evaluating it with
4868   // EvaluateAsBooleanCondition, but this uses a more direct technique:
4869   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
4870   if (!SrcArgDRE)
4871     return;
4872 
4873   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
4874   if (!CompareWithSrcDRE ||
4875       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
4876     return;
4877 
4878   const Expr *OriginalSizeArg = Call->getArg(2);
4879   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
4880     << OriginalSizeArg->getSourceRange() << FnName;
4881 
4882   // Output a FIXIT hint if the destination is an array (rather than a
4883   // pointer to an array).  This could be enhanced to handle some
4884   // pointers if we know the actual size, like if DstArg is 'array+2'
4885   // we could say 'sizeof(array)-2'.
4886   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
4887   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
4888     return;
4889 
4890   SmallString<128> sizeString;
4891   llvm::raw_svector_ostream OS(sizeString);
4892   OS << "sizeof(";
4893   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4894   OS << ")";
4895 
4896   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
4897     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
4898                                     OS.str());
4899 }
4900 
4901 /// Check if two expressions refer to the same declaration.
4902 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
4903   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
4904     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
4905       return D1->getDecl() == D2->getDecl();
4906   return false;
4907 }
4908 
4909 static const Expr *getStrlenExprArg(const Expr *E) {
4910   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
4911     const FunctionDecl *FD = CE->getDirectCallee();
4912     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
4913       return nullptr;
4914     return CE->getArg(0)->IgnoreParenCasts();
4915   }
4916   return nullptr;
4917 }
4918 
4919 // Warn on anti-patterns as the 'size' argument to strncat.
4920 // The correct size argument should look like following:
4921 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
4922 void Sema::CheckStrncatArguments(const CallExpr *CE,
4923                                  IdentifierInfo *FnName) {
4924   // Don't crash if the user has the wrong number of arguments.
4925   if (CE->getNumArgs() < 3)
4926     return;
4927   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
4928   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
4929   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
4930 
4931   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
4932                                      CE->getRParenLoc()))
4933     return;
4934 
4935   // Identify common expressions, which are wrongly used as the size argument
4936   // to strncat and may lead to buffer overflows.
4937   unsigned PatternType = 0;
4938   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
4939     // - sizeof(dst)
4940     if (referToTheSameDecl(SizeOfArg, DstArg))
4941       PatternType = 1;
4942     // - sizeof(src)
4943     else if (referToTheSameDecl(SizeOfArg, SrcArg))
4944       PatternType = 2;
4945   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
4946     if (BE->getOpcode() == BO_Sub) {
4947       const Expr *L = BE->getLHS()->IgnoreParenCasts();
4948       const Expr *R = BE->getRHS()->IgnoreParenCasts();
4949       // - sizeof(dst) - strlen(dst)
4950       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
4951           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
4952         PatternType = 1;
4953       // - sizeof(src) - (anything)
4954       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
4955         PatternType = 2;
4956     }
4957   }
4958 
4959   if (PatternType == 0)
4960     return;
4961 
4962   // Generate the diagnostic.
4963   SourceLocation SL = LenArg->getLocStart();
4964   SourceRange SR = LenArg->getSourceRange();
4965   SourceManager &SM = getSourceManager();
4966 
4967   // If the function is defined as a builtin macro, do not show macro expansion.
4968   if (SM.isMacroArgExpansion(SL)) {
4969     SL = SM.getSpellingLoc(SL);
4970     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
4971                      SM.getSpellingLoc(SR.getEnd()));
4972   }
4973 
4974   // Check if the destination is an array (rather than a pointer to an array).
4975   QualType DstTy = DstArg->getType();
4976   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
4977                                                                     Context);
4978   if (!isKnownSizeArray) {
4979     if (PatternType == 1)
4980       Diag(SL, diag::warn_strncat_wrong_size) << SR;
4981     else
4982       Diag(SL, diag::warn_strncat_src_size) << SR;
4983     return;
4984   }
4985 
4986   if (PatternType == 1)
4987     Diag(SL, diag::warn_strncat_large_size) << SR;
4988   else
4989     Diag(SL, diag::warn_strncat_src_size) << SR;
4990 
4991   SmallString<128> sizeString;
4992   llvm::raw_svector_ostream OS(sizeString);
4993   OS << "sizeof(";
4994   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4995   OS << ") - ";
4996   OS << "strlen(";
4997   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
4998   OS << ") - 1";
4999 
5000   Diag(SL, diag::note_strncat_wrong_size)
5001     << FixItHint::CreateReplacement(SR, OS.str());
5002 }
5003 
5004 //===--- CHECK: Return Address of Stack Variable --------------------------===//
5005 
5006 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5007                      Decl *ParentDecl);
5008 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
5009                       Decl *ParentDecl);
5010 
5011 /// CheckReturnStackAddr - Check if a return statement returns the address
5012 ///   of a stack variable.
5013 static void
5014 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
5015                      SourceLocation ReturnLoc) {
5016 
5017   Expr *stackE = nullptr;
5018   SmallVector<DeclRefExpr *, 8> refVars;
5019 
5020   // Perform checking for returned stack addresses, local blocks,
5021   // label addresses or references to temporaries.
5022   if (lhsType->isPointerType() ||
5023       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
5024     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
5025   } else if (lhsType->isReferenceType()) {
5026     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
5027   }
5028 
5029   if (!stackE)
5030     return; // Nothing suspicious was found.
5031 
5032   SourceLocation diagLoc;
5033   SourceRange diagRange;
5034   if (refVars.empty()) {
5035     diagLoc = stackE->getLocStart();
5036     diagRange = stackE->getSourceRange();
5037   } else {
5038     // We followed through a reference variable. 'stackE' contains the
5039     // problematic expression but we will warn at the return statement pointing
5040     // at the reference variable. We will later display the "trail" of
5041     // reference variables using notes.
5042     diagLoc = refVars[0]->getLocStart();
5043     diagRange = refVars[0]->getSourceRange();
5044   }
5045 
5046   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
5047     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
5048                                              : diag::warn_ret_stack_addr)
5049      << DR->getDecl()->getDeclName() << diagRange;
5050   } else if (isa<BlockExpr>(stackE)) { // local block.
5051     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
5052   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
5053     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
5054   } else { // local temporary.
5055     S.Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
5056                                                : diag::warn_ret_local_temp_addr)
5057      << diagRange;
5058   }
5059 
5060   // Display the "trail" of reference variables that we followed until we
5061   // found the problematic expression using notes.
5062   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
5063     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5064     // If this var binds to another reference var, show the range of the next
5065     // var, otherwise the var binds to the problematic expression, in which case
5066     // show the range of the expression.
5067     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5068                                   : stackE->getSourceRange();
5069     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
5070         << VD->getDeclName() << range;
5071   }
5072 }
5073 
5074 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
5075 ///  check if the expression in a return statement evaluates to an address
5076 ///  to a location on the stack, a local block, an address of a label, or a
5077 ///  reference to local temporary. The recursion is used to traverse the
5078 ///  AST of the return expression, with recursion backtracking when we
5079 ///  encounter a subexpression that (1) clearly does not lead to one of the
5080 ///  above problematic expressions (2) is something we cannot determine leads to
5081 ///  a problematic expression based on such local checking.
5082 ///
5083 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
5084 ///  the expression that they point to. Such variables are added to the
5085 ///  'refVars' vector so that we know what the reference variable "trail" was.
5086 ///
5087 ///  EvalAddr processes expressions that are pointers that are used as
5088 ///  references (and not L-values).  EvalVal handles all other values.
5089 ///  At the base case of the recursion is a check for the above problematic
5090 ///  expressions.
5091 ///
5092 ///  This implementation handles:
5093 ///
5094 ///   * pointer-to-pointer casts
5095 ///   * implicit conversions from array references to pointers
5096 ///   * taking the address of fields
5097 ///   * arbitrary interplay between "&" and "*" operators
5098 ///   * pointer arithmetic from an address of a stack variable
5099 ///   * taking the address of an array element where the array is on the stack
5100 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5101                       Decl *ParentDecl) {
5102   if (E->isTypeDependent())
5103     return nullptr;
5104 
5105   // We should only be called for evaluating pointer expressions.
5106   assert((E->getType()->isAnyPointerType() ||
5107           E->getType()->isBlockPointerType() ||
5108           E->getType()->isObjCQualifiedIdType()) &&
5109          "EvalAddr only works on pointers");
5110 
5111   E = E->IgnoreParens();
5112 
5113   // Our "symbolic interpreter" is just a dispatch off the currently
5114   // viewed AST node.  We then recursively traverse the AST by calling
5115   // EvalAddr and EvalVal appropriately.
5116   switch (E->getStmtClass()) {
5117   case Stmt::DeclRefExprClass: {
5118     DeclRefExpr *DR = cast<DeclRefExpr>(E);
5119 
5120     // If we leave the immediate function, the lifetime isn't about to end.
5121     if (DR->refersToEnclosingVariableOrCapture())
5122       return nullptr;
5123 
5124     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
5125       // If this is a reference variable, follow through to the expression that
5126       // it points to.
5127       if (V->hasLocalStorage() &&
5128           V->getType()->isReferenceType() && V->hasInit()) {
5129         // Add the reference variable to the "trail".
5130         refVars.push_back(DR);
5131         return EvalAddr(V->getInit(), refVars, ParentDecl);
5132       }
5133 
5134     return nullptr;
5135   }
5136 
5137   case Stmt::UnaryOperatorClass: {
5138     // The only unary operator that make sense to handle here
5139     // is AddrOf.  All others don't make sense as pointers.
5140     UnaryOperator *U = cast<UnaryOperator>(E);
5141 
5142     if (U->getOpcode() == UO_AddrOf)
5143       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
5144     else
5145       return nullptr;
5146   }
5147 
5148   case Stmt::BinaryOperatorClass: {
5149     // Handle pointer arithmetic.  All other binary operators are not valid
5150     // in this context.
5151     BinaryOperator *B = cast<BinaryOperator>(E);
5152     BinaryOperatorKind op = B->getOpcode();
5153 
5154     if (op != BO_Add && op != BO_Sub)
5155       return nullptr;
5156 
5157     Expr *Base = B->getLHS();
5158 
5159     // Determine which argument is the real pointer base.  It could be
5160     // the RHS argument instead of the LHS.
5161     if (!Base->getType()->isPointerType()) Base = B->getRHS();
5162 
5163     assert (Base->getType()->isPointerType());
5164     return EvalAddr(Base, refVars, ParentDecl);
5165   }
5166 
5167   // For conditional operators we need to see if either the LHS or RHS are
5168   // valid DeclRefExpr*s.  If one of them is valid, we return it.
5169   case Stmt::ConditionalOperatorClass: {
5170     ConditionalOperator *C = cast<ConditionalOperator>(E);
5171 
5172     // Handle the GNU extension for missing LHS.
5173     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
5174     if (Expr *LHSExpr = C->getLHS()) {
5175       // In C++, we can have a throw-expression, which has 'void' type.
5176       if (!LHSExpr->getType()->isVoidType())
5177         if (Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
5178           return LHS;
5179     }
5180 
5181     // In C++, we can have a throw-expression, which has 'void' type.
5182     if (C->getRHS()->getType()->isVoidType())
5183       return nullptr;
5184 
5185     return EvalAddr(C->getRHS(), refVars, ParentDecl);
5186   }
5187 
5188   case Stmt::BlockExprClass:
5189     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
5190       return E; // local block.
5191     return nullptr;
5192 
5193   case Stmt::AddrLabelExprClass:
5194     return E; // address of label.
5195 
5196   case Stmt::ExprWithCleanupsClass:
5197     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5198                     ParentDecl);
5199 
5200   // For casts, we need to handle conversions from arrays to
5201   // pointer values, and pointer-to-pointer conversions.
5202   case Stmt::ImplicitCastExprClass:
5203   case Stmt::CStyleCastExprClass:
5204   case Stmt::CXXFunctionalCastExprClass:
5205   case Stmt::ObjCBridgedCastExprClass:
5206   case Stmt::CXXStaticCastExprClass:
5207   case Stmt::CXXDynamicCastExprClass:
5208   case Stmt::CXXConstCastExprClass:
5209   case Stmt::CXXReinterpretCastExprClass: {
5210     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5211     switch (cast<CastExpr>(E)->getCastKind()) {
5212     case CK_LValueToRValue:
5213     case CK_NoOp:
5214     case CK_BaseToDerived:
5215     case CK_DerivedToBase:
5216     case CK_UncheckedDerivedToBase:
5217     case CK_Dynamic:
5218     case CK_CPointerToObjCPointerCast:
5219     case CK_BlockPointerToObjCPointerCast:
5220     case CK_AnyPointerToBlockPointerCast:
5221       return EvalAddr(SubExpr, refVars, ParentDecl);
5222 
5223     case CK_ArrayToPointerDecay:
5224       return EvalVal(SubExpr, refVars, ParentDecl);
5225 
5226     case CK_BitCast:
5227       if (SubExpr->getType()->isAnyPointerType() ||
5228           SubExpr->getType()->isBlockPointerType() ||
5229           SubExpr->getType()->isObjCQualifiedIdType())
5230         return EvalAddr(SubExpr, refVars, ParentDecl);
5231       else
5232         return nullptr;
5233 
5234     default:
5235       return nullptr;
5236     }
5237   }
5238 
5239   case Stmt::MaterializeTemporaryExprClass:
5240     if (Expr *Result = EvalAddr(
5241                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5242                                 refVars, ParentDecl))
5243       return Result;
5244 
5245     return E;
5246 
5247   // Everything else: we simply don't reason about them.
5248   default:
5249     return nullptr;
5250   }
5251 }
5252 
5253 
5254 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
5255 ///   See the comments for EvalAddr for more details.
5256 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5257                      Decl *ParentDecl) {
5258 do {
5259   // We should only be called for evaluating non-pointer expressions, or
5260   // expressions with a pointer type that are not used as references but instead
5261   // are l-values (e.g., DeclRefExpr with a pointer type).
5262 
5263   // Our "symbolic interpreter" is just a dispatch off the currently
5264   // viewed AST node.  We then recursively traverse the AST by calling
5265   // EvalAddr and EvalVal appropriately.
5266 
5267   E = E->IgnoreParens();
5268   switch (E->getStmtClass()) {
5269   case Stmt::ImplicitCastExprClass: {
5270     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
5271     if (IE->getValueKind() == VK_LValue) {
5272       E = IE->getSubExpr();
5273       continue;
5274     }
5275     return nullptr;
5276   }
5277 
5278   case Stmt::ExprWithCleanupsClass:
5279     return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
5280 
5281   case Stmt::DeclRefExprClass: {
5282     // When we hit a DeclRefExpr we are looking at code that refers to a
5283     // variable's name. If it's not a reference variable we check if it has
5284     // local storage within the function, and if so, return the expression.
5285     DeclRefExpr *DR = cast<DeclRefExpr>(E);
5286 
5287     // If we leave the immediate function, the lifetime isn't about to end.
5288     if (DR->refersToEnclosingVariableOrCapture())
5289       return nullptr;
5290 
5291     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
5292       // Check if it refers to itself, e.g. "int& i = i;".
5293       if (V == ParentDecl)
5294         return DR;
5295 
5296       if (V->hasLocalStorage()) {
5297         if (!V->getType()->isReferenceType())
5298           return DR;
5299 
5300         // Reference variable, follow through to the expression that
5301         // it points to.
5302         if (V->hasInit()) {
5303           // Add the reference variable to the "trail".
5304           refVars.push_back(DR);
5305           return EvalVal(V->getInit(), refVars, V);
5306         }
5307       }
5308     }
5309 
5310     return nullptr;
5311   }
5312 
5313   case Stmt::UnaryOperatorClass: {
5314     // The only unary operator that make sense to handle here
5315     // is Deref.  All others don't resolve to a "name."  This includes
5316     // handling all sorts of rvalues passed to a unary operator.
5317     UnaryOperator *U = cast<UnaryOperator>(E);
5318 
5319     if (U->getOpcode() == UO_Deref)
5320       return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
5321 
5322     return nullptr;
5323   }
5324 
5325   case Stmt::ArraySubscriptExprClass: {
5326     // Array subscripts are potential references to data on the stack.  We
5327     // retrieve the DeclRefExpr* for the array variable if it indeed
5328     // has local storage.
5329     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
5330   }
5331 
5332   case Stmt::ConditionalOperatorClass: {
5333     // For conditional operators we need to see if either the LHS or RHS are
5334     // non-NULL Expr's.  If one is non-NULL, we return it.
5335     ConditionalOperator *C = cast<ConditionalOperator>(E);
5336 
5337     // Handle the GNU extension for missing LHS.
5338     if (Expr *LHSExpr = C->getLHS()) {
5339       // In C++, we can have a throw-expression, which has 'void' type.
5340       if (!LHSExpr->getType()->isVoidType())
5341         if (Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
5342           return LHS;
5343     }
5344 
5345     // In C++, we can have a throw-expression, which has 'void' type.
5346     if (C->getRHS()->getType()->isVoidType())
5347       return nullptr;
5348 
5349     return EvalVal(C->getRHS(), refVars, ParentDecl);
5350   }
5351 
5352   // Accesses to members are potential references to data on the stack.
5353   case Stmt::MemberExprClass: {
5354     MemberExpr *M = cast<MemberExpr>(E);
5355 
5356     // Check for indirect access.  We only want direct field accesses.
5357     if (M->isArrow())
5358       return nullptr;
5359 
5360     // Check whether the member type is itself a reference, in which case
5361     // we're not going to refer to the member, but to what the member refers to.
5362     if (M->getMemberDecl()->getType()->isReferenceType())
5363       return nullptr;
5364 
5365     return EvalVal(M->getBase(), refVars, ParentDecl);
5366   }
5367 
5368   case Stmt::MaterializeTemporaryExprClass:
5369     if (Expr *Result = EvalVal(
5370                           cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5371                                refVars, ParentDecl))
5372       return Result;
5373 
5374     return E;
5375 
5376   default:
5377     // Check that we don't return or take the address of a reference to a
5378     // temporary. This is only useful in C++.
5379     if (!E->isTypeDependent() && E->isRValue())
5380       return E;
5381 
5382     // Everything else: we simply don't reason about them.
5383     return nullptr;
5384   }
5385 } while (true);
5386 }
5387 
5388 void
5389 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
5390                          SourceLocation ReturnLoc,
5391                          bool isObjCMethod,
5392                          const AttrVec *Attrs,
5393                          const FunctionDecl *FD) {
5394   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
5395 
5396   // Check if the return value is null but should not be.
5397   if (Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs) &&
5398       CheckNonNullExpr(*this, RetValExp))
5399     Diag(ReturnLoc, diag::warn_null_ret)
5400       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
5401 
5402   // C++11 [basic.stc.dynamic.allocation]p4:
5403   //   If an allocation function declared with a non-throwing
5404   //   exception-specification fails to allocate storage, it shall return
5405   //   a null pointer. Any other allocation function that fails to allocate
5406   //   storage shall indicate failure only by throwing an exception [...]
5407   if (FD) {
5408     OverloadedOperatorKind Op = FD->getOverloadedOperator();
5409     if (Op == OO_New || Op == OO_Array_New) {
5410       const FunctionProtoType *Proto
5411         = FD->getType()->castAs<FunctionProtoType>();
5412       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
5413           CheckNonNullExpr(*this, RetValExp))
5414         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5415           << FD << getLangOpts().CPlusPlus11;
5416     }
5417   }
5418 }
5419 
5420 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
5421 
5422 /// Check for comparisons of floating point operands using != and ==.
5423 /// Issue a warning if these are no self-comparisons, as they are not likely
5424 /// to do what the programmer intended.
5425 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
5426   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
5427   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
5428 
5429   // Special case: check for x == x (which is OK).
5430   // Do not emit warnings for such cases.
5431   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5432     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5433       if (DRL->getDecl() == DRR->getDecl())
5434         return;
5435 
5436 
5437   // Special case: check for comparisons against literals that can be exactly
5438   //  represented by APFloat.  In such cases, do not emit a warning.  This
5439   //  is a heuristic: often comparison against such literals are used to
5440   //  detect if a value in a variable has not changed.  This clearly can
5441   //  lead to false negatives.
5442   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5443     if (FLL->isExact())
5444       return;
5445   } else
5446     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5447       if (FLR->isExact())
5448         return;
5449 
5450   // Check for comparisons with builtin types.
5451   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
5452     if (CL->getBuiltinCallee())
5453       return;
5454 
5455   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
5456     if (CR->getBuiltinCallee())
5457       return;
5458 
5459   // Emit the diagnostic.
5460   Diag(Loc, diag::warn_floatingpoint_eq)
5461     << LHS->getSourceRange() << RHS->getSourceRange();
5462 }
5463 
5464 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
5465 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
5466 
5467 namespace {
5468 
5469 /// Structure recording the 'active' range of an integer-valued
5470 /// expression.
5471 struct IntRange {
5472   /// The number of bits active in the int.
5473   unsigned Width;
5474 
5475   /// True if the int is known not to have negative values.
5476   bool NonNegative;
5477 
5478   IntRange(unsigned Width, bool NonNegative)
5479     : Width(Width), NonNegative(NonNegative)
5480   {}
5481 
5482   /// Returns the range of the bool type.
5483   static IntRange forBoolType() {
5484     return IntRange(1, true);
5485   }
5486 
5487   /// Returns the range of an opaque value of the given integral type.
5488   static IntRange forValueOfType(ASTContext &C, QualType T) {
5489     return forValueOfCanonicalType(C,
5490                           T->getCanonicalTypeInternal().getTypePtr());
5491   }
5492 
5493   /// Returns the range of an opaque value of a canonical integral type.
5494   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
5495     assert(T->isCanonicalUnqualified());
5496 
5497     if (const VectorType *VT = dyn_cast<VectorType>(T))
5498       T = VT->getElementType().getTypePtr();
5499     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5500       T = CT->getElementType().getTypePtr();
5501     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5502       T = AT->getValueType().getTypePtr();
5503 
5504     // For enum types, use the known bit width of the enumerators.
5505     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
5506       EnumDecl *Enum = ET->getDecl();
5507       if (!Enum->isCompleteDefinition())
5508         return IntRange(C.getIntWidth(QualType(T, 0)), false);
5509 
5510       unsigned NumPositive = Enum->getNumPositiveBits();
5511       unsigned NumNegative = Enum->getNumNegativeBits();
5512 
5513       if (NumNegative == 0)
5514         return IntRange(NumPositive, true/*NonNegative*/);
5515       else
5516         return IntRange(std::max(NumPositive + 1, NumNegative),
5517                         false/*NonNegative*/);
5518     }
5519 
5520     const BuiltinType *BT = cast<BuiltinType>(T);
5521     assert(BT->isInteger());
5522 
5523     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5524   }
5525 
5526   /// Returns the "target" range of a canonical integral type, i.e.
5527   /// the range of values expressible in the type.
5528   ///
5529   /// This matches forValueOfCanonicalType except that enums have the
5530   /// full range of their type, not the range of their enumerators.
5531   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
5532     assert(T->isCanonicalUnqualified());
5533 
5534     if (const VectorType *VT = dyn_cast<VectorType>(T))
5535       T = VT->getElementType().getTypePtr();
5536     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
5537       T = CT->getElementType().getTypePtr();
5538     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
5539       T = AT->getValueType().getTypePtr();
5540     if (const EnumType *ET = dyn_cast<EnumType>(T))
5541       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
5542 
5543     const BuiltinType *BT = cast<BuiltinType>(T);
5544     assert(BT->isInteger());
5545 
5546     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
5547   }
5548 
5549   /// Returns the supremum of two ranges: i.e. their conservative merge.
5550   static IntRange join(IntRange L, IntRange R) {
5551     return IntRange(std::max(L.Width, R.Width),
5552                     L.NonNegative && R.NonNegative);
5553   }
5554 
5555   /// Returns the infinum of two ranges: i.e. their aggressive merge.
5556   static IntRange meet(IntRange L, IntRange R) {
5557     return IntRange(std::min(L.Width, R.Width),
5558                     L.NonNegative || R.NonNegative);
5559   }
5560 };
5561 
5562 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
5563                               unsigned MaxWidth) {
5564   if (value.isSigned() && value.isNegative())
5565     return IntRange(value.getMinSignedBits(), false);
5566 
5567   if (value.getBitWidth() > MaxWidth)
5568     value = value.trunc(MaxWidth);
5569 
5570   // isNonNegative() just checks the sign bit without considering
5571   // signedness.
5572   return IntRange(value.getActiveBits(), true);
5573 }
5574 
5575 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
5576                               unsigned MaxWidth) {
5577   if (result.isInt())
5578     return GetValueRange(C, result.getInt(), MaxWidth);
5579 
5580   if (result.isVector()) {
5581     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
5582     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
5583       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
5584       R = IntRange::join(R, El);
5585     }
5586     return R;
5587   }
5588 
5589   if (result.isComplexInt()) {
5590     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
5591     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
5592     return IntRange::join(R, I);
5593   }
5594 
5595   // This can happen with lossless casts to intptr_t of "based" lvalues.
5596   // Assume it might use arbitrary bits.
5597   // FIXME: The only reason we need to pass the type in here is to get
5598   // the sign right on this one case.  It would be nice if APValue
5599   // preserved this.
5600   assert(result.isLValue() || result.isAddrLabelDiff());
5601   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
5602 }
5603 
5604 static QualType GetExprType(Expr *E) {
5605   QualType Ty = E->getType();
5606   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
5607     Ty = AtomicRHS->getValueType();
5608   return Ty;
5609 }
5610 
5611 /// Pseudo-evaluate the given integer expression, estimating the
5612 /// range of values it might take.
5613 ///
5614 /// \param MaxWidth - the width to which the value will be truncated
5615 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
5616   E = E->IgnoreParens();
5617 
5618   // Try a full evaluation first.
5619   Expr::EvalResult result;
5620   if (E->EvaluateAsRValue(result, C))
5621     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
5622 
5623   // I think we only want to look through implicit casts here; if the
5624   // user has an explicit widening cast, we should treat the value as
5625   // being of the new, wider type.
5626   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
5627     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
5628       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
5629 
5630     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
5631 
5632     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
5633 
5634     // Assume that non-integer casts can span the full range of the type.
5635     if (!isIntegerCast)
5636       return OutputTypeRange;
5637 
5638     IntRange SubRange
5639       = GetExprRange(C, CE->getSubExpr(),
5640                      std::min(MaxWidth, OutputTypeRange.Width));
5641 
5642     // Bail out if the subexpr's range is as wide as the cast type.
5643     if (SubRange.Width >= OutputTypeRange.Width)
5644       return OutputTypeRange;
5645 
5646     // Otherwise, we take the smaller width, and we're non-negative if
5647     // either the output type or the subexpr is.
5648     return IntRange(SubRange.Width,
5649                     SubRange.NonNegative || OutputTypeRange.NonNegative);
5650   }
5651 
5652   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
5653     // If we can fold the condition, just take that operand.
5654     bool CondResult;
5655     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
5656       return GetExprRange(C, CondResult ? CO->getTrueExpr()
5657                                         : CO->getFalseExpr(),
5658                           MaxWidth);
5659 
5660     // Otherwise, conservatively merge.
5661     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
5662     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
5663     return IntRange::join(L, R);
5664   }
5665 
5666   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5667     switch (BO->getOpcode()) {
5668 
5669     // Boolean-valued operations are single-bit and positive.
5670     case BO_LAnd:
5671     case BO_LOr:
5672     case BO_LT:
5673     case BO_GT:
5674     case BO_LE:
5675     case BO_GE:
5676     case BO_EQ:
5677     case BO_NE:
5678       return IntRange::forBoolType();
5679 
5680     // The type of the assignments is the type of the LHS, so the RHS
5681     // is not necessarily the same type.
5682     case BO_MulAssign:
5683     case BO_DivAssign:
5684     case BO_RemAssign:
5685     case BO_AddAssign:
5686     case BO_SubAssign:
5687     case BO_XorAssign:
5688     case BO_OrAssign:
5689       // TODO: bitfields?
5690       return IntRange::forValueOfType(C, GetExprType(E));
5691 
5692     // Simple assignments just pass through the RHS, which will have
5693     // been coerced to the LHS type.
5694     case BO_Assign:
5695       // TODO: bitfields?
5696       return GetExprRange(C, BO->getRHS(), MaxWidth);
5697 
5698     // Operations with opaque sources are black-listed.
5699     case BO_PtrMemD:
5700     case BO_PtrMemI:
5701       return IntRange::forValueOfType(C, GetExprType(E));
5702 
5703     // Bitwise-and uses the *infinum* of the two source ranges.
5704     case BO_And:
5705     case BO_AndAssign:
5706       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
5707                             GetExprRange(C, BO->getRHS(), MaxWidth));
5708 
5709     // Left shift gets black-listed based on a judgement call.
5710     case BO_Shl:
5711       // ...except that we want to treat '1 << (blah)' as logically
5712       // positive.  It's an important idiom.
5713       if (IntegerLiteral *I
5714             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
5715         if (I->getValue() == 1) {
5716           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
5717           return IntRange(R.Width, /*NonNegative*/ true);
5718         }
5719       }
5720       // fallthrough
5721 
5722     case BO_ShlAssign:
5723       return IntRange::forValueOfType(C, GetExprType(E));
5724 
5725     // Right shift by a constant can narrow its left argument.
5726     case BO_Shr:
5727     case BO_ShrAssign: {
5728       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5729 
5730       // If the shift amount is a positive constant, drop the width by
5731       // that much.
5732       llvm::APSInt shift;
5733       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
5734           shift.isNonNegative()) {
5735         unsigned zext = shift.getZExtValue();
5736         if (zext >= L.Width)
5737           L.Width = (L.NonNegative ? 0 : 1);
5738         else
5739           L.Width -= zext;
5740       }
5741 
5742       return L;
5743     }
5744 
5745     // Comma acts as its right operand.
5746     case BO_Comma:
5747       return GetExprRange(C, BO->getRHS(), MaxWidth);
5748 
5749     // Black-list pointer subtractions.
5750     case BO_Sub:
5751       if (BO->getLHS()->getType()->isPointerType())
5752         return IntRange::forValueOfType(C, GetExprType(E));
5753       break;
5754 
5755     // The width of a division result is mostly determined by the size
5756     // of the LHS.
5757     case BO_Div: {
5758       // Don't 'pre-truncate' the operands.
5759       unsigned opWidth = C.getIntWidth(GetExprType(E));
5760       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5761 
5762       // If the divisor is constant, use that.
5763       llvm::APSInt divisor;
5764       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
5765         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
5766         if (log2 >= L.Width)
5767           L.Width = (L.NonNegative ? 0 : 1);
5768         else
5769           L.Width = std::min(L.Width - log2, MaxWidth);
5770         return L;
5771       }
5772 
5773       // Otherwise, just use the LHS's width.
5774       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5775       return IntRange(L.Width, L.NonNegative && R.NonNegative);
5776     }
5777 
5778     // The result of a remainder can't be larger than the result of
5779     // either side.
5780     case BO_Rem: {
5781       // Don't 'pre-truncate' the operands.
5782       unsigned opWidth = C.getIntWidth(GetExprType(E));
5783       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
5784       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
5785 
5786       IntRange meet = IntRange::meet(L, R);
5787       meet.Width = std::min(meet.Width, MaxWidth);
5788       return meet;
5789     }
5790 
5791     // The default behavior is okay for these.
5792     case BO_Mul:
5793     case BO_Add:
5794     case BO_Xor:
5795     case BO_Or:
5796       break;
5797     }
5798 
5799     // The default case is to treat the operation as if it were closed
5800     // on the narrowest type that encompasses both operands.
5801     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
5802     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
5803     return IntRange::join(L, R);
5804   }
5805 
5806   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5807     switch (UO->getOpcode()) {
5808     // Boolean-valued operations are white-listed.
5809     case UO_LNot:
5810       return IntRange::forBoolType();
5811 
5812     // Operations with opaque sources are black-listed.
5813     case UO_Deref:
5814     case UO_AddrOf: // should be impossible
5815       return IntRange::forValueOfType(C, GetExprType(E));
5816 
5817     default:
5818       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
5819     }
5820   }
5821 
5822   if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5823     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
5824 
5825   if (FieldDecl *BitField = E->getSourceBitField())
5826     return IntRange(BitField->getBitWidthValue(C),
5827                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
5828 
5829   return IntRange::forValueOfType(C, GetExprType(E));
5830 }
5831 
5832 static IntRange GetExprRange(ASTContext &C, Expr *E) {
5833   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
5834 }
5835 
5836 /// Checks whether the given value, which currently has the given
5837 /// source semantics, has the same value when coerced through the
5838 /// target semantics.
5839 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
5840                                  const llvm::fltSemantics &Src,
5841                                  const llvm::fltSemantics &Tgt) {
5842   llvm::APFloat truncated = value;
5843 
5844   bool ignored;
5845   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
5846   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
5847 
5848   return truncated.bitwiseIsEqual(value);
5849 }
5850 
5851 /// Checks whether the given value, which currently has the given
5852 /// source semantics, has the same value when coerced through the
5853 /// target semantics.
5854 ///
5855 /// The value might be a vector of floats (or a complex number).
5856 static bool IsSameFloatAfterCast(const APValue &value,
5857                                  const llvm::fltSemantics &Src,
5858                                  const llvm::fltSemantics &Tgt) {
5859   if (value.isFloat())
5860     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
5861 
5862   if (value.isVector()) {
5863     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
5864       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
5865         return false;
5866     return true;
5867   }
5868 
5869   assert(value.isComplexFloat());
5870   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
5871           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
5872 }
5873 
5874 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
5875 
5876 static bool IsZero(Sema &S, Expr *E) {
5877   // Suppress cases where we are comparing against an enum constant.
5878   if (const DeclRefExpr *DR =
5879       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
5880     if (isa<EnumConstantDecl>(DR->getDecl()))
5881       return false;
5882 
5883   // Suppress cases where the '0' value is expanded from a macro.
5884   if (E->getLocStart().isMacroID())
5885     return false;
5886 
5887   llvm::APSInt Value;
5888   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
5889 }
5890 
5891 static bool HasEnumType(Expr *E) {
5892   // Strip off implicit integral promotions.
5893   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5894     if (ICE->getCastKind() != CK_IntegralCast &&
5895         ICE->getCastKind() != CK_NoOp)
5896       break;
5897     E = ICE->getSubExpr();
5898   }
5899 
5900   return E->getType()->isEnumeralType();
5901 }
5902 
5903 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
5904   // Disable warning in template instantiations.
5905   if (!S.ActiveTemplateInstantiations.empty())
5906     return;
5907 
5908   BinaryOperatorKind op = E->getOpcode();
5909   if (E->isValueDependent())
5910     return;
5911 
5912   if (op == BO_LT && IsZero(S, E->getRHS())) {
5913     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5914       << "< 0" << "false" << HasEnumType(E->getLHS())
5915       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5916   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
5917     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
5918       << ">= 0" << "true" << HasEnumType(E->getLHS())
5919       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5920   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
5921     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5922       << "0 >" << "false" << HasEnumType(E->getRHS())
5923       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5924   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
5925     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
5926       << "0 <=" << "true" << HasEnumType(E->getRHS())
5927       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
5928   }
5929 }
5930 
5931 static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
5932                                          Expr *Constant, Expr *Other,
5933                                          llvm::APSInt Value,
5934                                          bool RhsConstant) {
5935   // Disable warning in template instantiations.
5936   if (!S.ActiveTemplateInstantiations.empty())
5937     return;
5938 
5939   // TODO: Investigate using GetExprRange() to get tighter bounds
5940   // on the bit ranges.
5941   QualType OtherT = Other->getType();
5942   if (const AtomicType *AT = dyn_cast<AtomicType>(OtherT))
5943     OtherT = AT->getValueType();
5944   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
5945   unsigned OtherWidth = OtherRange.Width;
5946 
5947   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
5948 
5949   // 0 values are handled later by CheckTrivialUnsignedComparison().
5950   if ((Value == 0) && (!OtherIsBooleanType))
5951     return;
5952 
5953   BinaryOperatorKind op = E->getOpcode();
5954   bool IsTrue = true;
5955 
5956   // Used for diagnostic printout.
5957   enum {
5958     LiteralConstant = 0,
5959     CXXBoolLiteralTrue,
5960     CXXBoolLiteralFalse
5961   } LiteralOrBoolConstant = LiteralConstant;
5962 
5963   if (!OtherIsBooleanType) {
5964     QualType ConstantT = Constant->getType();
5965     QualType CommonT = E->getLHS()->getType();
5966 
5967     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
5968       return;
5969     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
5970            "comparison with non-integer type");
5971 
5972     bool ConstantSigned = ConstantT->isSignedIntegerType();
5973     bool CommonSigned = CommonT->isSignedIntegerType();
5974 
5975     bool EqualityOnly = false;
5976 
5977     if (CommonSigned) {
5978       // The common type is signed, therefore no signed to unsigned conversion.
5979       if (!OtherRange.NonNegative) {
5980         // Check that the constant is representable in type OtherT.
5981         if (ConstantSigned) {
5982           if (OtherWidth >= Value.getMinSignedBits())
5983             return;
5984         } else { // !ConstantSigned
5985           if (OtherWidth >= Value.getActiveBits() + 1)
5986             return;
5987         }
5988       } else { // !OtherSigned
5989                // Check that the constant is representable in type OtherT.
5990         // Negative values are out of range.
5991         if (ConstantSigned) {
5992           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
5993             return;
5994         } else { // !ConstantSigned
5995           if (OtherWidth >= Value.getActiveBits())
5996             return;
5997         }
5998       }
5999     } else { // !CommonSigned
6000       if (OtherRange.NonNegative) {
6001         if (OtherWidth >= Value.getActiveBits())
6002           return;
6003       } else { // OtherSigned
6004         assert(!ConstantSigned &&
6005                "Two signed types converted to unsigned types.");
6006         // Check to see if the constant is representable in OtherT.
6007         if (OtherWidth > Value.getActiveBits())
6008           return;
6009         // Check to see if the constant is equivalent to a negative value
6010         // cast to CommonT.
6011         if (S.Context.getIntWidth(ConstantT) ==
6012                 S.Context.getIntWidth(CommonT) &&
6013             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6014           return;
6015         // The constant value rests between values that OtherT can represent
6016         // after conversion.  Relational comparison still works, but equality
6017         // comparisons will be tautological.
6018         EqualityOnly = true;
6019       }
6020     }
6021 
6022     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6023 
6024     if (op == BO_EQ || op == BO_NE) {
6025       IsTrue = op == BO_NE;
6026     } else if (EqualityOnly) {
6027       return;
6028     } else if (RhsConstant) {
6029       if (op == BO_GT || op == BO_GE)
6030         IsTrue = !PositiveConstant;
6031       else // op == BO_LT || op == BO_LE
6032         IsTrue = PositiveConstant;
6033     } else {
6034       if (op == BO_LT || op == BO_LE)
6035         IsTrue = !PositiveConstant;
6036       else // op == BO_GT || op == BO_GE
6037         IsTrue = PositiveConstant;
6038     }
6039   } else {
6040     // Other isKnownToHaveBooleanValue
6041     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6042     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6043     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6044 
6045     static const struct LinkedConditions {
6046       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6047       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6048       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6049       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6050       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6051       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6052 
6053     } TruthTable = {
6054         // Constant on LHS.              | Constant on RHS.              |
6055         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
6056         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6057         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6058         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6059         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6060         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6061         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6062       };
6063 
6064     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6065 
6066     enum ConstantValue ConstVal = Zero;
6067     if (Value.isUnsigned() || Value.isNonNegative()) {
6068       if (Value == 0) {
6069         LiteralOrBoolConstant =
6070             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6071         ConstVal = Zero;
6072       } else if (Value == 1) {
6073         LiteralOrBoolConstant =
6074             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6075         ConstVal = One;
6076       } else {
6077         LiteralOrBoolConstant = LiteralConstant;
6078         ConstVal = GT_One;
6079       }
6080     } else {
6081       ConstVal = LT_Zero;
6082     }
6083 
6084     CompareBoolWithConstantResult CmpRes;
6085 
6086     switch (op) {
6087     case BO_LT:
6088       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6089       break;
6090     case BO_GT:
6091       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6092       break;
6093     case BO_LE:
6094       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6095       break;
6096     case BO_GE:
6097       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6098       break;
6099     case BO_EQ:
6100       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6101       break;
6102     case BO_NE:
6103       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6104       break;
6105     default:
6106       CmpRes = Unkwn;
6107       break;
6108     }
6109 
6110     if (CmpRes == AFals) {
6111       IsTrue = false;
6112     } else if (CmpRes == ATrue) {
6113       IsTrue = true;
6114     } else {
6115       return;
6116     }
6117   }
6118 
6119   // If this is a comparison to an enum constant, include that
6120   // constant in the diagnostic.
6121   const EnumConstantDecl *ED = nullptr;
6122   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6123     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6124 
6125   SmallString<64> PrettySourceValue;
6126   llvm::raw_svector_ostream OS(PrettySourceValue);
6127   if (ED)
6128     OS << '\'' << *ED << "' (" << Value << ")";
6129   else
6130     OS << Value;
6131 
6132   S.DiagRuntimeBehavior(
6133     E->getOperatorLoc(), E,
6134     S.PDiag(diag::warn_out_of_range_compare)
6135         << OS.str() << LiteralOrBoolConstant
6136         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
6137         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
6138 }
6139 
6140 /// Analyze the operands of the given comparison.  Implements the
6141 /// fallback case from AnalyzeComparison.
6142 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
6143   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6144   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6145 }
6146 
6147 /// \brief Implements -Wsign-compare.
6148 ///
6149 /// \param E the binary operator to check for warnings
6150 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
6151   // The type the comparison is being performed in.
6152   QualType T = E->getLHS()->getType();
6153 
6154   // Only analyze comparison operators where both sides have been converted to
6155   // the same type.
6156   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
6157     return AnalyzeImpConvsInComparison(S, E);
6158 
6159   // Don't analyze value-dependent comparisons directly.
6160   if (E->isValueDependent())
6161     return AnalyzeImpConvsInComparison(S, E);
6162 
6163   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
6164   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
6165 
6166   bool IsComparisonConstant = false;
6167 
6168   // Check whether an integer constant comparison results in a value
6169   // of 'true' or 'false'.
6170   if (T->isIntegralType(S.Context)) {
6171     llvm::APSInt RHSValue;
6172     bool IsRHSIntegralLiteral =
6173       RHS->isIntegerConstantExpr(RHSValue, S.Context);
6174     llvm::APSInt LHSValue;
6175     bool IsLHSIntegralLiteral =
6176       LHS->isIntegerConstantExpr(LHSValue, S.Context);
6177     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6178         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
6179     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6180       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
6181     else
6182       IsComparisonConstant =
6183         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
6184   } else if (!T->hasUnsignedIntegerRepresentation())
6185       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
6186 
6187   // We don't do anything special if this isn't an unsigned integral
6188   // comparison:  we're only interested in integral comparisons, and
6189   // signed comparisons only happen in cases we don't care to warn about.
6190   //
6191   // We also don't care about value-dependent expressions or expressions
6192   // whose result is a constant.
6193   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
6194     return AnalyzeImpConvsInComparison(S, E);
6195 
6196   // Check to see if one of the (unmodified) operands is of different
6197   // signedness.
6198   Expr *signedOperand, *unsignedOperand;
6199   if (LHS->getType()->hasSignedIntegerRepresentation()) {
6200     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
6201            "unsigned comparison between two signed integer expressions?");
6202     signedOperand = LHS;
6203     unsignedOperand = RHS;
6204   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
6205     signedOperand = RHS;
6206     unsignedOperand = LHS;
6207   } else {
6208     CheckTrivialUnsignedComparison(S, E);
6209     return AnalyzeImpConvsInComparison(S, E);
6210   }
6211 
6212   // Otherwise, calculate the effective range of the signed operand.
6213   IntRange signedRange = GetExprRange(S.Context, signedOperand);
6214 
6215   // Go ahead and analyze implicit conversions in the operands.  Note
6216   // that we skip the implicit conversions on both sides.
6217   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
6218   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
6219 
6220   // If the signed range is non-negative, -Wsign-compare won't fire,
6221   // but we should still check for comparisons which are always true
6222   // or false.
6223   if (signedRange.NonNegative)
6224     return CheckTrivialUnsignedComparison(S, E);
6225 
6226   // For (in)equality comparisons, if the unsigned operand is a
6227   // constant which cannot collide with a overflowed signed operand,
6228   // then reinterpreting the signed operand as unsigned will not
6229   // change the result of the comparison.
6230   if (E->isEqualityOp()) {
6231     unsigned comparisonWidth = S.Context.getIntWidth(T);
6232     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
6233 
6234     // We should never be unable to prove that the unsigned operand is
6235     // non-negative.
6236     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
6237 
6238     if (unsignedRange.Width < comparisonWidth)
6239       return;
6240   }
6241 
6242   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
6243     S.PDiag(diag::warn_mixed_sign_comparison)
6244       << LHS->getType() << RHS->getType()
6245       << LHS->getSourceRange() << RHS->getSourceRange());
6246 }
6247 
6248 /// Analyzes an attempt to assign the given value to a bitfield.
6249 ///
6250 /// Returns true if there was something fishy about the attempt.
6251 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
6252                                       SourceLocation InitLoc) {
6253   assert(Bitfield->isBitField());
6254   if (Bitfield->isInvalidDecl())
6255     return false;
6256 
6257   // White-list bool bitfields.
6258   if (Bitfield->getType()->isBooleanType())
6259     return false;
6260 
6261   // Ignore value- or type-dependent expressions.
6262   if (Bitfield->getBitWidth()->isValueDependent() ||
6263       Bitfield->getBitWidth()->isTypeDependent() ||
6264       Init->isValueDependent() ||
6265       Init->isTypeDependent())
6266     return false;
6267 
6268   Expr *OriginalInit = Init->IgnoreParenImpCasts();
6269 
6270   llvm::APSInt Value;
6271   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
6272     return false;
6273 
6274   unsigned OriginalWidth = Value.getBitWidth();
6275   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
6276 
6277   if (OriginalWidth <= FieldWidth)
6278     return false;
6279 
6280   // Compute the value which the bitfield will contain.
6281   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
6282   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
6283 
6284   // Check whether the stored value is equal to the original value.
6285   TruncatedValue = TruncatedValue.extend(OriginalWidth);
6286   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
6287     return false;
6288 
6289   // Special-case bitfields of width 1: booleans are naturally 0/1, and
6290   // therefore don't strictly fit into a signed bitfield of width 1.
6291   if (FieldWidth == 1 && Value == 1)
6292     return false;
6293 
6294   std::string PrettyValue = Value.toString(10);
6295   std::string PrettyTrunc = TruncatedValue.toString(10);
6296 
6297   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6298     << PrettyValue << PrettyTrunc << OriginalInit->getType()
6299     << Init->getSourceRange();
6300 
6301   return true;
6302 }
6303 
6304 /// Analyze the given simple or compound assignment for warning-worthy
6305 /// operations.
6306 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
6307   // Just recurse on the LHS.
6308   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
6309 
6310   // We want to recurse on the RHS as normal unless we're assigning to
6311   // a bitfield.
6312   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
6313     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
6314                                   E->getOperatorLoc())) {
6315       // Recurse, ignoring any implicit conversions on the RHS.
6316       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
6317                                         E->getOperatorLoc());
6318     }
6319   }
6320 
6321   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
6322 }
6323 
6324 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
6325 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
6326                             SourceLocation CContext, unsigned diag,
6327                             bool pruneControlFlow = false) {
6328   if (pruneControlFlow) {
6329     S.DiagRuntimeBehavior(E->getExprLoc(), E,
6330                           S.PDiag(diag)
6331                             << SourceType << T << E->getSourceRange()
6332                             << SourceRange(CContext));
6333     return;
6334   }
6335   S.Diag(E->getExprLoc(), diag)
6336     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
6337 }
6338 
6339 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
6340 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
6341                             SourceLocation CContext, unsigned diag,
6342                             bool pruneControlFlow = false) {
6343   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
6344 }
6345 
6346 /// Diagnose an implicit cast from a literal expression. Does not warn when the
6347 /// cast wouldn't lose information.
6348 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
6349                                     SourceLocation CContext) {
6350   // Try to convert the literal exactly to an integer. If we can, don't warn.
6351   bool isExact = false;
6352   const llvm::APFloat &Value = FL->getValue();
6353   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
6354                             T->hasUnsignedIntegerRepresentation());
6355   if (Value.convertToInteger(IntegerValue,
6356                              llvm::APFloat::rmTowardZero, &isExact)
6357       == llvm::APFloat::opOK && isExact)
6358     return;
6359 
6360   // FIXME: Force the precision of the source value down so we don't print
6361   // digits which are usually useless (we don't really care here if we
6362   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
6363   // would automatically print the shortest representation, but it's a bit
6364   // tricky to implement.
6365   SmallString<16> PrettySourceValue;
6366   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6367   precision = (precision * 59 + 195) / 196;
6368   Value.toString(PrettySourceValue, precision);
6369 
6370   SmallString<16> PrettyTargetValue;
6371   if (T->isSpecificBuiltinType(BuiltinType::Bool))
6372     PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
6373   else
6374     IntegerValue.toString(PrettyTargetValue);
6375 
6376   S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
6377     << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
6378     << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
6379 }
6380 
6381 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
6382   if (!Range.Width) return "0";
6383 
6384   llvm::APSInt ValueInRange = Value;
6385   ValueInRange.setIsSigned(!Range.NonNegative);
6386   ValueInRange = ValueInRange.trunc(Range.Width);
6387   return ValueInRange.toString(10);
6388 }
6389 
6390 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
6391   if (!isa<ImplicitCastExpr>(Ex))
6392     return false;
6393 
6394   Expr *InnerE = Ex->IgnoreParenImpCasts();
6395   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
6396   const Type *Source =
6397     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6398   if (Target->isDependentType())
6399     return false;
6400 
6401   const BuiltinType *FloatCandidateBT =
6402     dyn_cast<BuiltinType>(ToBool ? Source : Target);
6403   const Type *BoolCandidateType = ToBool ? Target : Source;
6404 
6405   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6406           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
6407 }
6408 
6409 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
6410                                       SourceLocation CC) {
6411   unsigned NumArgs = TheCall->getNumArgs();
6412   for (unsigned i = 0; i < NumArgs; ++i) {
6413     Expr *CurrA = TheCall->getArg(i);
6414     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
6415       continue;
6416 
6417     bool IsSwapped = ((i > 0) &&
6418         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
6419     IsSwapped |= ((i < (NumArgs - 1)) &&
6420         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
6421     if (IsSwapped) {
6422       // Warn on this floating-point to bool conversion.
6423       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
6424                       CurrA->getType(), CC,
6425                       diag::warn_impcast_floating_point_to_bool);
6426     }
6427   }
6428 }
6429 
6430 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
6431                                    SourceLocation CC) {
6432   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
6433                         E->getExprLoc()))
6434     return;
6435 
6436   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
6437   const Expr::NullPointerConstantKind NullKind =
6438       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
6439   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
6440     return;
6441 
6442   // Return if target type is a safe conversion.
6443   if (T->isAnyPointerType() || T->isBlockPointerType() ||
6444       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
6445     return;
6446 
6447   SourceLocation Loc = E->getSourceRange().getBegin();
6448 
6449   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
6450   if (NullKind == Expr::NPCK_GNUNull) {
6451     if (Loc.isMacroID())
6452       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
6453   }
6454 
6455   // Only warn if the null and context location are in the same macro expansion.
6456   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
6457     return;
6458 
6459   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6460       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
6461       << FixItHint::CreateReplacement(Loc,
6462                                       S.getFixItZeroLiteralForType(T, Loc));
6463 }
6464 
6465 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
6466                              SourceLocation CC, bool *ICContext = nullptr) {
6467   if (E->isTypeDependent() || E->isValueDependent()) return;
6468 
6469   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
6470   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
6471   if (Source == Target) return;
6472   if (Target->isDependentType()) return;
6473 
6474   // If the conversion context location is invalid don't complain. We also
6475   // don't want to emit a warning if the issue occurs from the expansion of
6476   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
6477   // delay this check as long as possible. Once we detect we are in that
6478   // scenario, we just return.
6479   if (CC.isInvalid())
6480     return;
6481 
6482   // Diagnose implicit casts to bool.
6483   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
6484     if (isa<StringLiteral>(E))
6485       // Warn on string literal to bool.  Checks for string literals in logical
6486       // and expressions, for instance, assert(0 && "error here"), are
6487       // prevented by a check in AnalyzeImplicitConversions().
6488       return DiagnoseImpCast(S, E, T, CC,
6489                              diag::warn_impcast_string_literal_to_bool);
6490     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
6491         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
6492       // This covers the literal expressions that evaluate to Objective-C
6493       // objects.
6494       return DiagnoseImpCast(S, E, T, CC,
6495                              diag::warn_impcast_objective_c_literal_to_bool);
6496     }
6497     if (Source->isPointerType() || Source->canDecayToPointerType()) {
6498       // Warn on pointer to bool conversion that is always true.
6499       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
6500                                      SourceRange(CC));
6501     }
6502   }
6503 
6504   // Strip vector types.
6505   if (isa<VectorType>(Source)) {
6506     if (!isa<VectorType>(Target)) {
6507       if (S.SourceMgr.isInSystemMacro(CC))
6508         return;
6509       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
6510     }
6511 
6512     // If the vector cast is cast between two vectors of the same size, it is
6513     // a bitcast, not a conversion.
6514     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
6515       return;
6516 
6517     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
6518     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
6519   }
6520   if (auto VecTy = dyn_cast<VectorType>(Target))
6521     Target = VecTy->getElementType().getTypePtr();
6522 
6523   // Strip complex types.
6524   if (isa<ComplexType>(Source)) {
6525     if (!isa<ComplexType>(Target)) {
6526       if (S.SourceMgr.isInSystemMacro(CC))
6527         return;
6528 
6529       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
6530     }
6531 
6532     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
6533     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
6534   }
6535 
6536   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
6537   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
6538 
6539   // If the source is floating point...
6540   if (SourceBT && SourceBT->isFloatingPoint()) {
6541     // ...and the target is floating point...
6542     if (TargetBT && TargetBT->isFloatingPoint()) {
6543       // ...then warn if we're dropping FP rank.
6544 
6545       // Builtin FP kinds are ordered by increasing FP rank.
6546       if (SourceBT->getKind() > TargetBT->getKind()) {
6547         // Don't warn about float constants that are precisely
6548         // representable in the target type.
6549         Expr::EvalResult result;
6550         if (E->EvaluateAsRValue(result, S.Context)) {
6551           // Value might be a float, a float vector, or a float complex.
6552           if (IsSameFloatAfterCast(result.Val,
6553                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
6554                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
6555             return;
6556         }
6557 
6558         if (S.SourceMgr.isInSystemMacro(CC))
6559           return;
6560 
6561         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
6562       }
6563       return;
6564     }
6565 
6566     // If the target is integral, always warn.
6567     if (TargetBT && TargetBT->isInteger()) {
6568       if (S.SourceMgr.isInSystemMacro(CC))
6569         return;
6570 
6571       Expr *InnerE = E->IgnoreParenImpCasts();
6572       // We also want to warn on, e.g., "int i = -1.234"
6573       if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
6574         if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
6575           InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
6576 
6577       if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
6578         DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
6579       } else {
6580         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
6581       }
6582     }
6583 
6584     // If the target is bool, warn if expr is a function or method call.
6585     if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
6586         isa<CallExpr>(E)) {
6587       // Check last argument of function call to see if it is an
6588       // implicit cast from a type matching the type the result
6589       // is being cast to.
6590       CallExpr *CEx = cast<CallExpr>(E);
6591       unsigned NumArgs = CEx->getNumArgs();
6592       if (NumArgs > 0) {
6593         Expr *LastA = CEx->getArg(NumArgs - 1);
6594         Expr *InnerE = LastA->IgnoreParenImpCasts();
6595         const Type *InnerType =
6596           S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
6597         if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
6598           // Warn on this floating-point to bool conversion
6599           DiagnoseImpCast(S, E, T, CC,
6600                           diag::warn_impcast_floating_point_to_bool);
6601         }
6602       }
6603     }
6604     return;
6605   }
6606 
6607   DiagnoseNullConversion(S, E, T, CC);
6608 
6609   if (!Source->isIntegerType() || !Target->isIntegerType())
6610     return;
6611 
6612   // TODO: remove this early return once the false positives for constant->bool
6613   // in templates, macros, etc, are reduced or removed.
6614   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
6615     return;
6616 
6617   IntRange SourceRange = GetExprRange(S.Context, E);
6618   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
6619 
6620   if (SourceRange.Width > TargetRange.Width) {
6621     // If the source is a constant, use a default-on diagnostic.
6622     // TODO: this should happen for bitfield stores, too.
6623     llvm::APSInt Value(32);
6624     if (E->isIntegerConstantExpr(Value, S.Context)) {
6625       if (S.SourceMgr.isInSystemMacro(CC))
6626         return;
6627 
6628       std::string PrettySourceValue = Value.toString(10);
6629       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
6630 
6631       S.DiagRuntimeBehavior(E->getExprLoc(), E,
6632         S.PDiag(diag::warn_impcast_integer_precision_constant)
6633             << PrettySourceValue << PrettyTargetValue
6634             << E->getType() << T << E->getSourceRange()
6635             << clang::SourceRange(CC));
6636       return;
6637     }
6638 
6639     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
6640     if (S.SourceMgr.isInSystemMacro(CC))
6641       return;
6642 
6643     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
6644       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
6645                              /* pruneControlFlow */ true);
6646     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
6647   }
6648 
6649   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
6650       (!TargetRange.NonNegative && SourceRange.NonNegative &&
6651        SourceRange.Width == TargetRange.Width)) {
6652 
6653     if (S.SourceMgr.isInSystemMacro(CC))
6654       return;
6655 
6656     unsigned DiagID = diag::warn_impcast_integer_sign;
6657 
6658     // Traditionally, gcc has warned about this under -Wsign-compare.
6659     // We also want to warn about it in -Wconversion.
6660     // So if -Wconversion is off, use a completely identical diagnostic
6661     // in the sign-compare group.
6662     // The conditional-checking code will
6663     if (ICContext) {
6664       DiagID = diag::warn_impcast_integer_sign_conditional;
6665       *ICContext = true;
6666     }
6667 
6668     return DiagnoseImpCast(S, E, T, CC, DiagID);
6669   }
6670 
6671   // Diagnose conversions between different enumeration types.
6672   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
6673   // type, to give us better diagnostics.
6674   QualType SourceType = E->getType();
6675   if (!S.getLangOpts().CPlusPlus) {
6676     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
6677       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
6678         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
6679         SourceType = S.Context.getTypeDeclType(Enum);
6680         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
6681       }
6682   }
6683 
6684   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
6685     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
6686       if (SourceEnum->getDecl()->hasNameForLinkage() &&
6687           TargetEnum->getDecl()->hasNameForLinkage() &&
6688           SourceEnum != TargetEnum) {
6689         if (S.SourceMgr.isInSystemMacro(CC))
6690           return;
6691 
6692         return DiagnoseImpCast(S, E, SourceType, T, CC,
6693                                diag::warn_impcast_different_enum_types);
6694       }
6695 
6696   return;
6697 }
6698 
6699 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6700                               SourceLocation CC, QualType T);
6701 
6702 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
6703                              SourceLocation CC, bool &ICContext) {
6704   E = E->IgnoreParenImpCasts();
6705 
6706   if (isa<ConditionalOperator>(E))
6707     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
6708 
6709   AnalyzeImplicitConversions(S, E, CC);
6710   if (E->getType() != T)
6711     return CheckImplicitConversion(S, E, T, CC, &ICContext);
6712   return;
6713 }
6714 
6715 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
6716                               SourceLocation CC, QualType T) {
6717   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
6718 
6719   bool Suspicious = false;
6720   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
6721   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
6722 
6723   // If -Wconversion would have warned about either of the candidates
6724   // for a signedness conversion to the context type...
6725   if (!Suspicious) return;
6726 
6727   // ...but it's currently ignored...
6728   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
6729     return;
6730 
6731   // ...then check whether it would have warned about either of the
6732   // candidates for a signedness conversion to the condition type.
6733   if (E->getType() == T) return;
6734 
6735   Suspicious = false;
6736   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
6737                           E->getType(), CC, &Suspicious);
6738   if (!Suspicious)
6739     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
6740                             E->getType(), CC, &Suspicious);
6741 }
6742 
6743 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
6744 /// Input argument E is a logical expression.
6745 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
6746   if (S.getLangOpts().Bool)
6747     return;
6748   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
6749 }
6750 
6751 /// AnalyzeImplicitConversions - Find and report any interesting
6752 /// implicit conversions in the given expression.  There are a couple
6753 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
6754 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
6755   QualType T = OrigE->getType();
6756   Expr *E = OrigE->IgnoreParenImpCasts();
6757 
6758   if (E->isTypeDependent() || E->isValueDependent())
6759     return;
6760 
6761   // For conditional operators, we analyze the arguments as if they
6762   // were being fed directly into the output.
6763   if (isa<ConditionalOperator>(E)) {
6764     ConditionalOperator *CO = cast<ConditionalOperator>(E);
6765     CheckConditionalOperator(S, CO, CC, T);
6766     return;
6767   }
6768 
6769   // Check implicit argument conversions for function calls.
6770   if (CallExpr *Call = dyn_cast<CallExpr>(E))
6771     CheckImplicitArgumentConversions(S, Call, CC);
6772 
6773   // Go ahead and check any implicit conversions we might have skipped.
6774   // The non-canonical typecheck is just an optimization;
6775   // CheckImplicitConversion will filter out dead implicit conversions.
6776   if (E->getType() != T)
6777     CheckImplicitConversion(S, E, T, CC);
6778 
6779   // Now continue drilling into this expression.
6780 
6781   if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
6782     if (POE->getResultExpr())
6783       E = POE->getResultExpr();
6784   }
6785 
6786   if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
6787     return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
6788 
6789   // Skip past explicit casts.
6790   if (isa<ExplicitCastExpr>(E)) {
6791     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
6792     return AnalyzeImplicitConversions(S, E, CC);
6793   }
6794 
6795   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6796     // Do a somewhat different check with comparison operators.
6797     if (BO->isComparisonOp())
6798       return AnalyzeComparison(S, BO);
6799 
6800     // And with simple assignments.
6801     if (BO->getOpcode() == BO_Assign)
6802       return AnalyzeAssignment(S, BO);
6803   }
6804 
6805   // These break the otherwise-useful invariant below.  Fortunately,
6806   // we don't really need to recurse into them, because any internal
6807   // expressions should have been analyzed already when they were
6808   // built into statements.
6809   if (isa<StmtExpr>(E)) return;
6810 
6811   // Don't descend into unevaluated contexts.
6812   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
6813 
6814   // Now just recurse over the expression's children.
6815   CC = E->getExprLoc();
6816   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
6817   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
6818   for (Stmt::child_range I = E->children(); I; ++I) {
6819     Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
6820     if (!ChildExpr)
6821       continue;
6822 
6823     if (IsLogicalAndOperator &&
6824         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
6825       // Ignore checking string literals that are in logical and operators.
6826       // This is a common pattern for asserts.
6827       continue;
6828     AnalyzeImplicitConversions(S, ChildExpr, CC);
6829   }
6830 
6831   if (BO && BO->isLogicalOp()) {
6832     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
6833     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
6834       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
6835 
6836     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
6837     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
6838       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
6839   }
6840 
6841   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
6842     if (U->getOpcode() == UO_LNot)
6843       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
6844 }
6845 
6846 } // end anonymous namespace
6847 
6848 enum {
6849   AddressOf,
6850   FunctionPointer,
6851   ArrayPointer
6852 };
6853 
6854 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
6855 // Returns true when emitting a warning about taking the address of a reference.
6856 static bool CheckForReference(Sema &SemaRef, const Expr *E,
6857                               PartialDiagnostic PD) {
6858   E = E->IgnoreParenImpCasts();
6859 
6860   const FunctionDecl *FD = nullptr;
6861 
6862   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6863     if (!DRE->getDecl()->getType()->isReferenceType())
6864       return false;
6865   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6866     if (!M->getMemberDecl()->getType()->isReferenceType())
6867       return false;
6868   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
6869     if (!Call->getCallReturnType()->isReferenceType())
6870       return false;
6871     FD = Call->getDirectCallee();
6872   } else {
6873     return false;
6874   }
6875 
6876   SemaRef.Diag(E->getExprLoc(), PD);
6877 
6878   // If possible, point to location of function.
6879   if (FD) {
6880     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
6881   }
6882 
6883   return true;
6884 }
6885 
6886 // Returns true if the SourceLocation is expanded from any macro body.
6887 // Returns false if the SourceLocation is invalid, is from not in a macro
6888 // expansion, or is from expanded from a top-level macro argument.
6889 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
6890   if (Loc.isInvalid())
6891     return false;
6892 
6893   while (Loc.isMacroID()) {
6894     if (SM.isMacroBodyExpansion(Loc))
6895       return true;
6896     Loc = SM.getImmediateMacroCallerLoc(Loc);
6897   }
6898 
6899   return false;
6900 }
6901 
6902 /// \brief Diagnose pointers that are always non-null.
6903 /// \param E the expression containing the pointer
6904 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
6905 /// compared to a null pointer
6906 /// \param IsEqual True when the comparison is equal to a null pointer
6907 /// \param Range Extra SourceRange to highlight in the diagnostic
6908 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
6909                                         Expr::NullPointerConstantKind NullKind,
6910                                         bool IsEqual, SourceRange Range) {
6911   if (!E)
6912     return;
6913 
6914   // Don't warn inside macros.
6915   if (E->getExprLoc().isMacroID()) {
6916     const SourceManager &SM = getSourceManager();
6917     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
6918         IsInAnyMacroBody(SM, Range.getBegin()))
6919       return;
6920   }
6921   E = E->IgnoreImpCasts();
6922 
6923   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
6924 
6925   if (isa<CXXThisExpr>(E)) {
6926     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
6927                                 : diag::warn_this_bool_conversion;
6928     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
6929     return;
6930   }
6931 
6932   bool IsAddressOf = false;
6933 
6934   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
6935     if (UO->getOpcode() != UO_AddrOf)
6936       return;
6937     IsAddressOf = true;
6938     E = UO->getSubExpr();
6939   }
6940 
6941   if (IsAddressOf) {
6942     unsigned DiagID = IsCompare
6943                           ? diag::warn_address_of_reference_null_compare
6944                           : diag::warn_address_of_reference_bool_conversion;
6945     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
6946                                          << IsEqual;
6947     if (CheckForReference(*this, E, PD)) {
6948       return;
6949     }
6950   }
6951 
6952   // Expect to find a single Decl.  Skip anything more complicated.
6953   ValueDecl *D = nullptr;
6954   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
6955     D = R->getDecl();
6956   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
6957     D = M->getMemberDecl();
6958   }
6959 
6960   // Weak Decls can be null.
6961   if (!D || D->isWeak())
6962     return;
6963 
6964   // Check for parameter decl with nonnull attribute
6965   if (const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
6966     if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
6967       if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
6968         unsigned NumArgs = FD->getNumParams();
6969         llvm::SmallBitVector AttrNonNull(NumArgs);
6970         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
6971           if (!NonNull->args_size()) {
6972             AttrNonNull.set(0, NumArgs);
6973             break;
6974           }
6975           for (unsigned Val : NonNull->args()) {
6976             if (Val >= NumArgs)
6977               continue;
6978             AttrNonNull.set(Val);
6979           }
6980         }
6981         if (!AttrNonNull.empty())
6982           for (unsigned i = 0; i < NumArgs; ++i)
6983             if (FD->getParamDecl(i) == PV &&
6984                 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
6985               std::string Str;
6986               llvm::raw_string_ostream S(Str);
6987               E->printPretty(S, nullptr, getPrintingPolicy());
6988               unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
6989                                           : diag::warn_cast_nonnull_to_bool;
6990               Diag(E->getExprLoc(), DiagID) << S.str() << E->getSourceRange()
6991                 << Range << IsEqual;
6992               return;
6993             }
6994       }
6995     }
6996 
6997   QualType T = D->getType();
6998   const bool IsArray = T->isArrayType();
6999   const bool IsFunction = T->isFunctionType();
7000 
7001   // Address of function is used to silence the function warning.
7002   if (IsAddressOf && IsFunction) {
7003     return;
7004   }
7005 
7006   // Found nothing.
7007   if (!IsAddressOf && !IsFunction && !IsArray)
7008     return;
7009 
7010   // Pretty print the expression for the diagnostic.
7011   std::string Str;
7012   llvm::raw_string_ostream S(Str);
7013   E->printPretty(S, nullptr, getPrintingPolicy());
7014 
7015   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7016                               : diag::warn_impcast_pointer_to_bool;
7017   unsigned DiagType;
7018   if (IsAddressOf)
7019     DiagType = AddressOf;
7020   else if (IsFunction)
7021     DiagType = FunctionPointer;
7022   else if (IsArray)
7023     DiagType = ArrayPointer;
7024   else
7025     llvm_unreachable("Could not determine diagnostic.");
7026   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7027                                 << Range << IsEqual;
7028 
7029   if (!IsFunction)
7030     return;
7031 
7032   // Suggest '&' to silence the function warning.
7033   Diag(E->getExprLoc(), diag::note_function_warning_silence)
7034       << FixItHint::CreateInsertion(E->getLocStart(), "&");
7035 
7036   // Check to see if '()' fixit should be emitted.
7037   QualType ReturnType;
7038   UnresolvedSet<4> NonTemplateOverloads;
7039   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7040   if (ReturnType.isNull())
7041     return;
7042 
7043   if (IsCompare) {
7044     // There are two cases here.  If there is null constant, the only suggest
7045     // for a pointer return type.  If the null is 0, then suggest if the return
7046     // type is a pointer or an integer type.
7047     if (!ReturnType->isPointerType()) {
7048       if (NullKind == Expr::NPCK_ZeroExpression ||
7049           NullKind == Expr::NPCK_ZeroLiteral) {
7050         if (!ReturnType->isIntegerType())
7051           return;
7052       } else {
7053         return;
7054       }
7055     }
7056   } else { // !IsCompare
7057     // For function to bool, only suggest if the function pointer has bool
7058     // return type.
7059     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7060       return;
7061   }
7062   Diag(E->getExprLoc(), diag::note_function_to_function_call)
7063       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
7064 }
7065 
7066 
7067 /// Diagnoses "dangerous" implicit conversions within the given
7068 /// expression (which is a full expression).  Implements -Wconversion
7069 /// and -Wsign-compare.
7070 ///
7071 /// \param CC the "context" location of the implicit conversion, i.e.
7072 ///   the most location of the syntactic entity requiring the implicit
7073 ///   conversion
7074 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
7075   // Don't diagnose in unevaluated contexts.
7076   if (isUnevaluatedContext())
7077     return;
7078 
7079   // Don't diagnose for value- or type-dependent expressions.
7080   if (E->isTypeDependent() || E->isValueDependent())
7081     return;
7082 
7083   // Check for array bounds violations in cases where the check isn't triggered
7084   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
7085   // ArraySubscriptExpr is on the RHS of a variable initialization.
7086   CheckArrayAccess(E);
7087 
7088   // This is not the right CC for (e.g.) a variable initialization.
7089   AnalyzeImplicitConversions(*this, E, CC);
7090 }
7091 
7092 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
7093 /// Input argument E is a logical expression.
7094 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
7095   ::CheckBoolLikeConversion(*this, E, CC);
7096 }
7097 
7098 /// Diagnose when expression is an integer constant expression and its evaluation
7099 /// results in integer overflow
7100 void Sema::CheckForIntOverflow (Expr *E) {
7101   if (isa<BinaryOperator>(E->IgnoreParenCasts()))
7102     E->IgnoreParenCasts()->EvaluateForOverflow(Context);
7103 }
7104 
7105 namespace {
7106 /// \brief Visitor for expressions which looks for unsequenced operations on the
7107 /// same object.
7108 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
7109   typedef EvaluatedExprVisitor<SequenceChecker> Base;
7110 
7111   /// \brief A tree of sequenced regions within an expression. Two regions are
7112   /// unsequenced if one is an ancestor or a descendent of the other. When we
7113   /// finish processing an expression with sequencing, such as a comma
7114   /// expression, we fold its tree nodes into its parent, since they are
7115   /// unsequenced with respect to nodes we will visit later.
7116   class SequenceTree {
7117     struct Value {
7118       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
7119       unsigned Parent : 31;
7120       bool Merged : 1;
7121     };
7122     SmallVector<Value, 8> Values;
7123 
7124   public:
7125     /// \brief A region within an expression which may be sequenced with respect
7126     /// to some other region.
7127     class Seq {
7128       explicit Seq(unsigned N) : Index(N) {}
7129       unsigned Index;
7130       friend class SequenceTree;
7131     public:
7132       Seq() : Index(0) {}
7133     };
7134 
7135     SequenceTree() { Values.push_back(Value(0)); }
7136     Seq root() const { return Seq(0); }
7137 
7138     /// \brief Create a new sequence of operations, which is an unsequenced
7139     /// subset of \p Parent. This sequence of operations is sequenced with
7140     /// respect to other children of \p Parent.
7141     Seq allocate(Seq Parent) {
7142       Values.push_back(Value(Parent.Index));
7143       return Seq(Values.size() - 1);
7144     }
7145 
7146     /// \brief Merge a sequence of operations into its parent.
7147     void merge(Seq S) {
7148       Values[S.Index].Merged = true;
7149     }
7150 
7151     /// \brief Determine whether two operations are unsequenced. This operation
7152     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
7153     /// should have been merged into its parent as appropriate.
7154     bool isUnsequenced(Seq Cur, Seq Old) {
7155       unsigned C = representative(Cur.Index);
7156       unsigned Target = representative(Old.Index);
7157       while (C >= Target) {
7158         if (C == Target)
7159           return true;
7160         C = Values[C].Parent;
7161       }
7162       return false;
7163     }
7164 
7165   private:
7166     /// \brief Pick a representative for a sequence.
7167     unsigned representative(unsigned K) {
7168       if (Values[K].Merged)
7169         // Perform path compression as we go.
7170         return Values[K].Parent = representative(Values[K].Parent);
7171       return K;
7172     }
7173   };
7174 
7175   /// An object for which we can track unsequenced uses.
7176   typedef NamedDecl *Object;
7177 
7178   /// Different flavors of object usage which we track. We only track the
7179   /// least-sequenced usage of each kind.
7180   enum UsageKind {
7181     /// A read of an object. Multiple unsequenced reads are OK.
7182     UK_Use,
7183     /// A modification of an object which is sequenced before the value
7184     /// computation of the expression, such as ++n in C++.
7185     UK_ModAsValue,
7186     /// A modification of an object which is not sequenced before the value
7187     /// computation of the expression, such as n++.
7188     UK_ModAsSideEffect,
7189 
7190     UK_Count = UK_ModAsSideEffect + 1
7191   };
7192 
7193   struct Usage {
7194     Usage() : Use(nullptr), Seq() {}
7195     Expr *Use;
7196     SequenceTree::Seq Seq;
7197   };
7198 
7199   struct UsageInfo {
7200     UsageInfo() : Diagnosed(false) {}
7201     Usage Uses[UK_Count];
7202     /// Have we issued a diagnostic for this variable already?
7203     bool Diagnosed;
7204   };
7205   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7206 
7207   Sema &SemaRef;
7208   /// Sequenced regions within the expression.
7209   SequenceTree Tree;
7210   /// Declaration modifications and references which we have seen.
7211   UsageInfoMap UsageMap;
7212   /// The region we are currently within.
7213   SequenceTree::Seq Region;
7214   /// Filled in with declarations which were modified as a side-effect
7215   /// (that is, post-increment operations).
7216   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
7217   /// Expressions to check later. We defer checking these to reduce
7218   /// stack usage.
7219   SmallVectorImpl<Expr *> &WorkList;
7220 
7221   /// RAII object wrapping the visitation of a sequenced subexpression of an
7222   /// expression. At the end of this process, the side-effects of the evaluation
7223   /// become sequenced with respect to the value computation of the result, so
7224   /// we downgrade any UK_ModAsSideEffect within the evaluation to
7225   /// UK_ModAsValue.
7226   struct SequencedSubexpression {
7227     SequencedSubexpression(SequenceChecker &Self)
7228       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7229       Self.ModAsSideEffect = &ModAsSideEffect;
7230     }
7231     ~SequencedSubexpression() {
7232       for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7233            MI != ME; ++MI) {
7234         UsageInfo &U = Self.UsageMap[MI->first];
7235         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7236         Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7237         SideEffectUsage = MI->second;
7238       }
7239       Self.ModAsSideEffect = OldModAsSideEffect;
7240     }
7241 
7242     SequenceChecker &Self;
7243     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
7244     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
7245   };
7246 
7247   /// RAII object wrapping the visitation of a subexpression which we might
7248   /// choose to evaluate as a constant. If any subexpression is evaluated and
7249   /// found to be non-constant, this allows us to suppress the evaluation of
7250   /// the outer expression.
7251   class EvaluationTracker {
7252   public:
7253     EvaluationTracker(SequenceChecker &Self)
7254         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
7255       Self.EvalTracker = this;
7256     }
7257     ~EvaluationTracker() {
7258       Self.EvalTracker = Prev;
7259       if (Prev)
7260         Prev->EvalOK &= EvalOK;
7261     }
7262 
7263     bool evaluate(const Expr *E, bool &Result) {
7264       if (!EvalOK || E->isValueDependent())
7265         return false;
7266       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
7267       return EvalOK;
7268     }
7269 
7270   private:
7271     SequenceChecker &Self;
7272     EvaluationTracker *Prev;
7273     bool EvalOK;
7274   } *EvalTracker;
7275 
7276   /// \brief Find the object which is produced by the specified expression,
7277   /// if any.
7278   Object getObject(Expr *E, bool Mod) const {
7279     E = E->IgnoreParenCasts();
7280     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
7281       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
7282         return getObject(UO->getSubExpr(), Mod);
7283     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7284       if (BO->getOpcode() == BO_Comma)
7285         return getObject(BO->getRHS(), Mod);
7286       if (Mod && BO->isAssignmentOp())
7287         return getObject(BO->getLHS(), Mod);
7288     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7289       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
7290       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7291         return ME->getMemberDecl();
7292     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7293       // FIXME: If this is a reference, map through to its value.
7294       return DRE->getDecl();
7295     return nullptr;
7296   }
7297 
7298   /// \brief Note that an object was modified or used by an expression.
7299   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
7300     Usage &U = UI.Uses[UK];
7301     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7302       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7303         ModAsSideEffect->push_back(std::make_pair(O, U));
7304       U.Use = Ref;
7305       U.Seq = Region;
7306     }
7307   }
7308   /// \brief Check whether a modification or use conflicts with a prior usage.
7309   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
7310                   bool IsModMod) {
7311     if (UI.Diagnosed)
7312       return;
7313 
7314     const Usage &U = UI.Uses[OtherKind];
7315     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7316       return;
7317 
7318     Expr *Mod = U.Use;
7319     Expr *ModOrUse = Ref;
7320     if (OtherKind == UK_Use)
7321       std::swap(Mod, ModOrUse);
7322 
7323     SemaRef.Diag(Mod->getExprLoc(),
7324                  IsModMod ? diag::warn_unsequenced_mod_mod
7325                           : diag::warn_unsequenced_mod_use)
7326       << O << SourceRange(ModOrUse->getExprLoc());
7327     UI.Diagnosed = true;
7328   }
7329 
7330   void notePreUse(Object O, Expr *Use) {
7331     UsageInfo &U = UsageMap[O];
7332     // Uses conflict with other modifications.
7333     checkUsage(O, U, Use, UK_ModAsValue, false);
7334   }
7335   void notePostUse(Object O, Expr *Use) {
7336     UsageInfo &U = UsageMap[O];
7337     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
7338     addUsage(U, O, Use, UK_Use);
7339   }
7340 
7341   void notePreMod(Object O, Expr *Mod) {
7342     UsageInfo &U = UsageMap[O];
7343     // Modifications conflict with other modifications and with uses.
7344     checkUsage(O, U, Mod, UK_ModAsValue, true);
7345     checkUsage(O, U, Mod, UK_Use, false);
7346   }
7347   void notePostMod(Object O, Expr *Use, UsageKind UK) {
7348     UsageInfo &U = UsageMap[O];
7349     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
7350     addUsage(U, O, Use, UK);
7351   }
7352 
7353 public:
7354   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
7355       : Base(S.Context), SemaRef(S), Region(Tree.root()),
7356         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
7357     Visit(E);
7358   }
7359 
7360   void VisitStmt(Stmt *S) {
7361     // Skip all statements which aren't expressions for now.
7362   }
7363 
7364   void VisitExpr(Expr *E) {
7365     // By default, just recurse to evaluated subexpressions.
7366     Base::VisitStmt(E);
7367   }
7368 
7369   void VisitCastExpr(CastExpr *E) {
7370     Object O = Object();
7371     if (E->getCastKind() == CK_LValueToRValue)
7372       O = getObject(E->getSubExpr(), false);
7373 
7374     if (O)
7375       notePreUse(O, E);
7376     VisitExpr(E);
7377     if (O)
7378       notePostUse(O, E);
7379   }
7380 
7381   void VisitBinComma(BinaryOperator *BO) {
7382     // C++11 [expr.comma]p1:
7383     //   Every value computation and side effect associated with the left
7384     //   expression is sequenced before every value computation and side
7385     //   effect associated with the right expression.
7386     SequenceTree::Seq LHS = Tree.allocate(Region);
7387     SequenceTree::Seq RHS = Tree.allocate(Region);
7388     SequenceTree::Seq OldRegion = Region;
7389 
7390     {
7391       SequencedSubexpression SeqLHS(*this);
7392       Region = LHS;
7393       Visit(BO->getLHS());
7394     }
7395 
7396     Region = RHS;
7397     Visit(BO->getRHS());
7398 
7399     Region = OldRegion;
7400 
7401     // Forget that LHS and RHS are sequenced. They are both unsequenced
7402     // with respect to other stuff.
7403     Tree.merge(LHS);
7404     Tree.merge(RHS);
7405   }
7406 
7407   void VisitBinAssign(BinaryOperator *BO) {
7408     // The modification is sequenced after the value computation of the LHS
7409     // and RHS, so check it before inspecting the operands and update the
7410     // map afterwards.
7411     Object O = getObject(BO->getLHS(), true);
7412     if (!O)
7413       return VisitExpr(BO);
7414 
7415     notePreMod(O, BO);
7416 
7417     // C++11 [expr.ass]p7:
7418     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
7419     //   only once.
7420     //
7421     // Therefore, for a compound assignment operator, O is considered used
7422     // everywhere except within the evaluation of E1 itself.
7423     if (isa<CompoundAssignOperator>(BO))
7424       notePreUse(O, BO);
7425 
7426     Visit(BO->getLHS());
7427 
7428     if (isa<CompoundAssignOperator>(BO))
7429       notePostUse(O, BO);
7430 
7431     Visit(BO->getRHS());
7432 
7433     // C++11 [expr.ass]p1:
7434     //   the assignment is sequenced [...] before the value computation of the
7435     //   assignment expression.
7436     // C11 6.5.16/3 has no such rule.
7437     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7438                                                        : UK_ModAsSideEffect);
7439   }
7440   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
7441     VisitBinAssign(CAO);
7442   }
7443 
7444   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7445   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7446   void VisitUnaryPreIncDec(UnaryOperator *UO) {
7447     Object O = getObject(UO->getSubExpr(), true);
7448     if (!O)
7449       return VisitExpr(UO);
7450 
7451     notePreMod(O, UO);
7452     Visit(UO->getSubExpr());
7453     // C++11 [expr.pre.incr]p1:
7454     //   the expression ++x is equivalent to x+=1
7455     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7456                                                        : UK_ModAsSideEffect);
7457   }
7458 
7459   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7460   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7461   void VisitUnaryPostIncDec(UnaryOperator *UO) {
7462     Object O = getObject(UO->getSubExpr(), true);
7463     if (!O)
7464       return VisitExpr(UO);
7465 
7466     notePreMod(O, UO);
7467     Visit(UO->getSubExpr());
7468     notePostMod(O, UO, UK_ModAsSideEffect);
7469   }
7470 
7471   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
7472   void VisitBinLOr(BinaryOperator *BO) {
7473     // The side-effects of the LHS of an '&&' are sequenced before the
7474     // value computation of the RHS, and hence before the value computation
7475     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
7476     // as if they were unconditionally sequenced.
7477     EvaluationTracker Eval(*this);
7478     {
7479       SequencedSubexpression Sequenced(*this);
7480       Visit(BO->getLHS());
7481     }
7482 
7483     bool Result;
7484     if (Eval.evaluate(BO->getLHS(), Result)) {
7485       if (!Result)
7486         Visit(BO->getRHS());
7487     } else {
7488       // Check for unsequenced operations in the RHS, treating it as an
7489       // entirely separate evaluation.
7490       //
7491       // FIXME: If there are operations in the RHS which are unsequenced
7492       // with respect to operations outside the RHS, and those operations
7493       // are unconditionally evaluated, diagnose them.
7494       WorkList.push_back(BO->getRHS());
7495     }
7496   }
7497   void VisitBinLAnd(BinaryOperator *BO) {
7498     EvaluationTracker Eval(*this);
7499     {
7500       SequencedSubexpression Sequenced(*this);
7501       Visit(BO->getLHS());
7502     }
7503 
7504     bool Result;
7505     if (Eval.evaluate(BO->getLHS(), Result)) {
7506       if (Result)
7507         Visit(BO->getRHS());
7508     } else {
7509       WorkList.push_back(BO->getRHS());
7510     }
7511   }
7512 
7513   // Only visit the condition, unless we can be sure which subexpression will
7514   // be chosen.
7515   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
7516     EvaluationTracker Eval(*this);
7517     {
7518       SequencedSubexpression Sequenced(*this);
7519       Visit(CO->getCond());
7520     }
7521 
7522     bool Result;
7523     if (Eval.evaluate(CO->getCond(), Result))
7524       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
7525     else {
7526       WorkList.push_back(CO->getTrueExpr());
7527       WorkList.push_back(CO->getFalseExpr());
7528     }
7529   }
7530 
7531   void VisitCallExpr(CallExpr *CE) {
7532     // C++11 [intro.execution]p15:
7533     //   When calling a function [...], every value computation and side effect
7534     //   associated with any argument expression, or with the postfix expression
7535     //   designating the called function, is sequenced before execution of every
7536     //   expression or statement in the body of the function [and thus before
7537     //   the value computation of its result].
7538     SequencedSubexpression Sequenced(*this);
7539     Base::VisitCallExpr(CE);
7540 
7541     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
7542   }
7543 
7544   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
7545     // This is a call, so all subexpressions are sequenced before the result.
7546     SequencedSubexpression Sequenced(*this);
7547 
7548     if (!CCE->isListInitialization())
7549       return VisitExpr(CCE);
7550 
7551     // In C++11, list initializations are sequenced.
7552     SmallVector<SequenceTree::Seq, 32> Elts;
7553     SequenceTree::Seq Parent = Region;
7554     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
7555                                         E = CCE->arg_end();
7556          I != E; ++I) {
7557       Region = Tree.allocate(Parent);
7558       Elts.push_back(Region);
7559       Visit(*I);
7560     }
7561 
7562     // Forget that the initializers are sequenced.
7563     Region = Parent;
7564     for (unsigned I = 0; I < Elts.size(); ++I)
7565       Tree.merge(Elts[I]);
7566   }
7567 
7568   void VisitInitListExpr(InitListExpr *ILE) {
7569     if (!SemaRef.getLangOpts().CPlusPlus11)
7570       return VisitExpr(ILE);
7571 
7572     // In C++11, list initializations are sequenced.
7573     SmallVector<SequenceTree::Seq, 32> Elts;
7574     SequenceTree::Seq Parent = Region;
7575     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
7576       Expr *E = ILE->getInit(I);
7577       if (!E) continue;
7578       Region = Tree.allocate(Parent);
7579       Elts.push_back(Region);
7580       Visit(E);
7581     }
7582 
7583     // Forget that the initializers are sequenced.
7584     Region = Parent;
7585     for (unsigned I = 0; I < Elts.size(); ++I)
7586       Tree.merge(Elts[I]);
7587   }
7588 };
7589 }
7590 
7591 void Sema::CheckUnsequencedOperations(Expr *E) {
7592   SmallVector<Expr *, 8> WorkList;
7593   WorkList.push_back(E);
7594   while (!WorkList.empty()) {
7595     Expr *Item = WorkList.pop_back_val();
7596     SequenceChecker(*this, Item, WorkList);
7597   }
7598 }
7599 
7600 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
7601                               bool IsConstexpr) {
7602   CheckImplicitConversions(E, CheckLoc);
7603   CheckUnsequencedOperations(E);
7604   if (!IsConstexpr && !E->isValueDependent())
7605     CheckForIntOverflow(E);
7606 }
7607 
7608 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
7609                                        FieldDecl *BitField,
7610                                        Expr *Init) {
7611   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
7612 }
7613 
7614 /// CheckParmsForFunctionDef - Check that the parameters of the given
7615 /// function are appropriate for the definition of a function. This
7616 /// takes care of any checks that cannot be performed on the
7617 /// declaration itself, e.g., that the types of each of the function
7618 /// parameters are complete.
7619 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
7620                                     ParmVarDecl *const *PEnd,
7621                                     bool CheckParameterNames) {
7622   bool HasInvalidParm = false;
7623   for (; P != PEnd; ++P) {
7624     ParmVarDecl *Param = *P;
7625 
7626     // C99 6.7.5.3p4: the parameters in a parameter type list in a
7627     // function declarator that is part of a function definition of
7628     // that function shall not have incomplete type.
7629     //
7630     // This is also C++ [dcl.fct]p6.
7631     if (!Param->isInvalidDecl() &&
7632         RequireCompleteType(Param->getLocation(), Param->getType(),
7633                             diag::err_typecheck_decl_incomplete_type)) {
7634       Param->setInvalidDecl();
7635       HasInvalidParm = true;
7636     }
7637 
7638     // C99 6.9.1p5: If the declarator includes a parameter type list, the
7639     // declaration of each parameter shall include an identifier.
7640     if (CheckParameterNames &&
7641         Param->getIdentifier() == nullptr &&
7642         !Param->isImplicit() &&
7643         !getLangOpts().CPlusPlus)
7644       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
7645 
7646     // C99 6.7.5.3p12:
7647     //   If the function declarator is not part of a definition of that
7648     //   function, parameters may have incomplete type and may use the [*]
7649     //   notation in their sequences of declarator specifiers to specify
7650     //   variable length array types.
7651     QualType PType = Param->getOriginalType();
7652     while (const ArrayType *AT = Context.getAsArrayType(PType)) {
7653       if (AT->getSizeModifier() == ArrayType::Star) {
7654         // FIXME: This diagnostic should point the '[*]' if source-location
7655         // information is added for it.
7656         Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
7657         break;
7658       }
7659       PType= AT->getElementType();
7660     }
7661 
7662     // MSVC destroys objects passed by value in the callee.  Therefore a
7663     // function definition which takes such a parameter must be able to call the
7664     // object's destructor.  However, we don't perform any direct access check
7665     // on the dtor.
7666     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
7667                                        .getCXXABI()
7668                                        .areArgsDestroyedLeftToRightInCallee()) {
7669       if (!Param->isInvalidDecl()) {
7670         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
7671           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
7672           if (!ClassDecl->isInvalidDecl() &&
7673               !ClassDecl->hasIrrelevantDestructor() &&
7674               !ClassDecl->isDependentContext()) {
7675             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
7676             MarkFunctionReferenced(Param->getLocation(), Destructor);
7677             DiagnoseUseOfDecl(Destructor, Param->getLocation());
7678           }
7679         }
7680       }
7681     }
7682   }
7683 
7684   return HasInvalidParm;
7685 }
7686 
7687 /// CheckCastAlign - Implements -Wcast-align, which warns when a
7688 /// pointer cast increases the alignment requirements.
7689 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
7690   // This is actually a lot of work to potentially be doing on every
7691   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
7692   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
7693     return;
7694 
7695   // Ignore dependent types.
7696   if (T->isDependentType() || Op->getType()->isDependentType())
7697     return;
7698 
7699   // Require that the destination be a pointer type.
7700   const PointerType *DestPtr = T->getAs<PointerType>();
7701   if (!DestPtr) return;
7702 
7703   // If the destination has alignment 1, we're done.
7704   QualType DestPointee = DestPtr->getPointeeType();
7705   if (DestPointee->isIncompleteType()) return;
7706   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
7707   if (DestAlign.isOne()) return;
7708 
7709   // Require that the source be a pointer type.
7710   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
7711   if (!SrcPtr) return;
7712   QualType SrcPointee = SrcPtr->getPointeeType();
7713 
7714   // Whitelist casts from cv void*.  We already implicitly
7715   // whitelisted casts to cv void*, since they have alignment 1.
7716   // Also whitelist casts involving incomplete types, which implicitly
7717   // includes 'void'.
7718   if (SrcPointee->isIncompleteType()) return;
7719 
7720   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
7721   if (SrcAlign >= DestAlign) return;
7722 
7723   Diag(TRange.getBegin(), diag::warn_cast_align)
7724     << Op->getType() << T
7725     << static_cast<unsigned>(SrcAlign.getQuantity())
7726     << static_cast<unsigned>(DestAlign.getQuantity())
7727     << TRange << Op->getSourceRange();
7728 }
7729 
7730 static const Type* getElementType(const Expr *BaseExpr) {
7731   const Type* EltType = BaseExpr->getType().getTypePtr();
7732   if (EltType->isAnyPointerType())
7733     return EltType->getPointeeType().getTypePtr();
7734   else if (EltType->isArrayType())
7735     return EltType->getBaseElementTypeUnsafe();
7736   return EltType;
7737 }
7738 
7739 /// \brief Check whether this array fits the idiom of a size-one tail padded
7740 /// array member of a struct.
7741 ///
7742 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
7743 /// commonly used to emulate flexible arrays in C89 code.
7744 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
7745                                     const NamedDecl *ND) {
7746   if (Size != 1 || !ND) return false;
7747 
7748   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
7749   if (!FD) return false;
7750 
7751   // Don't consider sizes resulting from macro expansions or template argument
7752   // substitution to form C89 tail-padded arrays.
7753 
7754   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
7755   while (TInfo) {
7756     TypeLoc TL = TInfo->getTypeLoc();
7757     // Look through typedefs.
7758     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
7759       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
7760       TInfo = TDL->getTypeSourceInfo();
7761       continue;
7762     }
7763     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
7764       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
7765       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
7766         return false;
7767     }
7768     break;
7769   }
7770 
7771   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
7772   if (!RD) return false;
7773   if (RD->isUnion()) return false;
7774   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
7775     if (!CRD->isStandardLayout()) return false;
7776   }
7777 
7778   // See if this is the last field decl in the record.
7779   const Decl *D = FD;
7780   while ((D = D->getNextDeclInContext()))
7781     if (isa<FieldDecl>(D))
7782       return false;
7783   return true;
7784 }
7785 
7786 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
7787                             const ArraySubscriptExpr *ASE,
7788                             bool AllowOnePastEnd, bool IndexNegated) {
7789   IndexExpr = IndexExpr->IgnoreParenImpCasts();
7790   if (IndexExpr->isValueDependent())
7791     return;
7792 
7793   const Type *EffectiveType = getElementType(BaseExpr);
7794   BaseExpr = BaseExpr->IgnoreParenCasts();
7795   const ConstantArrayType *ArrayTy =
7796     Context.getAsConstantArrayType(BaseExpr->getType());
7797   if (!ArrayTy)
7798     return;
7799 
7800   llvm::APSInt index;
7801   if (!IndexExpr->EvaluateAsInt(index, Context))
7802     return;
7803   if (IndexNegated)
7804     index = -index;
7805 
7806   const NamedDecl *ND = nullptr;
7807   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7808     ND = dyn_cast<NamedDecl>(DRE->getDecl());
7809   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7810     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7811 
7812   if (index.isUnsigned() || !index.isNegative()) {
7813     llvm::APInt size = ArrayTy->getSize();
7814     if (!size.isStrictlyPositive())
7815       return;
7816 
7817     const Type* BaseType = getElementType(BaseExpr);
7818     if (BaseType != EffectiveType) {
7819       // Make sure we're comparing apples to apples when comparing index to size
7820       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
7821       uint64_t array_typesize = Context.getTypeSize(BaseType);
7822       // Handle ptrarith_typesize being zero, such as when casting to void*
7823       if (!ptrarith_typesize) ptrarith_typesize = 1;
7824       if (ptrarith_typesize != array_typesize) {
7825         // There's a cast to a different size type involved
7826         uint64_t ratio = array_typesize / ptrarith_typesize;
7827         // TODO: Be smarter about handling cases where array_typesize is not a
7828         // multiple of ptrarith_typesize
7829         if (ptrarith_typesize * ratio == array_typesize)
7830           size *= llvm::APInt(size.getBitWidth(), ratio);
7831       }
7832     }
7833 
7834     if (size.getBitWidth() > index.getBitWidth())
7835       index = index.zext(size.getBitWidth());
7836     else if (size.getBitWidth() < index.getBitWidth())
7837       size = size.zext(index.getBitWidth());
7838 
7839     // For array subscripting the index must be less than size, but for pointer
7840     // arithmetic also allow the index (offset) to be equal to size since
7841     // computing the next address after the end of the array is legal and
7842     // commonly done e.g. in C++ iterators and range-based for loops.
7843     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
7844       return;
7845 
7846     // Also don't warn for arrays of size 1 which are members of some
7847     // structure. These are often used to approximate flexible arrays in C89
7848     // code.
7849     if (IsTailPaddedMemberArray(*this, size, ND))
7850       return;
7851 
7852     // Suppress the warning if the subscript expression (as identified by the
7853     // ']' location) and the index expression are both from macro expansions
7854     // within a system header.
7855     if (ASE) {
7856       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
7857           ASE->getRBracketLoc());
7858       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
7859         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
7860             IndexExpr->getLocStart());
7861         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
7862           return;
7863       }
7864     }
7865 
7866     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
7867     if (ASE)
7868       DiagID = diag::warn_array_index_exceeds_bounds;
7869 
7870     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7871                         PDiag(DiagID) << index.toString(10, true)
7872                           << size.toString(10, true)
7873                           << (unsigned)size.getLimitedValue(~0U)
7874                           << IndexExpr->getSourceRange());
7875   } else {
7876     unsigned DiagID = diag::warn_array_index_precedes_bounds;
7877     if (!ASE) {
7878       DiagID = diag::warn_ptr_arith_precedes_bounds;
7879       if (index.isNegative()) index = -index;
7880     }
7881 
7882     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
7883                         PDiag(DiagID) << index.toString(10, true)
7884                           << IndexExpr->getSourceRange());
7885   }
7886 
7887   if (!ND) {
7888     // Try harder to find a NamedDecl to point at in the note.
7889     while (const ArraySubscriptExpr *ASE =
7890            dyn_cast<ArraySubscriptExpr>(BaseExpr))
7891       BaseExpr = ASE->getBase()->IgnoreParenCasts();
7892     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
7893       ND = dyn_cast<NamedDecl>(DRE->getDecl());
7894     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
7895       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
7896   }
7897 
7898   if (ND)
7899     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
7900                         PDiag(diag::note_array_index_out_of_bounds)
7901                           << ND->getDeclName());
7902 }
7903 
7904 void Sema::CheckArrayAccess(const Expr *expr) {
7905   int AllowOnePastEnd = 0;
7906   while (expr) {
7907     expr = expr->IgnoreParenImpCasts();
7908     switch (expr->getStmtClass()) {
7909       case Stmt::ArraySubscriptExprClass: {
7910         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
7911         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
7912                          AllowOnePastEnd > 0);
7913         return;
7914       }
7915       case Stmt::UnaryOperatorClass: {
7916         // Only unwrap the * and & unary operators
7917         const UnaryOperator *UO = cast<UnaryOperator>(expr);
7918         expr = UO->getSubExpr();
7919         switch (UO->getOpcode()) {
7920           case UO_AddrOf:
7921             AllowOnePastEnd++;
7922             break;
7923           case UO_Deref:
7924             AllowOnePastEnd--;
7925             break;
7926           default:
7927             return;
7928         }
7929         break;
7930       }
7931       case Stmt::ConditionalOperatorClass: {
7932         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
7933         if (const Expr *lhs = cond->getLHS())
7934           CheckArrayAccess(lhs);
7935         if (const Expr *rhs = cond->getRHS())
7936           CheckArrayAccess(rhs);
7937         return;
7938       }
7939       default:
7940         return;
7941     }
7942   }
7943 }
7944 
7945 //===--- CHECK: Objective-C retain cycles ----------------------------------//
7946 
7947 namespace {
7948   struct RetainCycleOwner {
7949     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
7950     VarDecl *Variable;
7951     SourceRange Range;
7952     SourceLocation Loc;
7953     bool Indirect;
7954 
7955     void setLocsFrom(Expr *e) {
7956       Loc = e->getExprLoc();
7957       Range = e->getSourceRange();
7958     }
7959   };
7960 }
7961 
7962 /// Consider whether capturing the given variable can possibly lead to
7963 /// a retain cycle.
7964 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
7965   // In ARC, it's captured strongly iff the variable has __strong
7966   // lifetime.  In MRR, it's captured strongly if the variable is
7967   // __block and has an appropriate type.
7968   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7969     return false;
7970 
7971   owner.Variable = var;
7972   if (ref)
7973     owner.setLocsFrom(ref);
7974   return true;
7975 }
7976 
7977 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
7978   while (true) {
7979     e = e->IgnoreParens();
7980     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
7981       switch (cast->getCastKind()) {
7982       case CK_BitCast:
7983       case CK_LValueBitCast:
7984       case CK_LValueToRValue:
7985       case CK_ARCReclaimReturnedObject:
7986         e = cast->getSubExpr();
7987         continue;
7988 
7989       default:
7990         return false;
7991       }
7992     }
7993 
7994     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
7995       ObjCIvarDecl *ivar = ref->getDecl();
7996       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
7997         return false;
7998 
7999       // Try to find a retain cycle in the base.
8000       if (!findRetainCycleOwner(S, ref->getBase(), owner))
8001         return false;
8002 
8003       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8004       owner.Indirect = true;
8005       return true;
8006     }
8007 
8008     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8009       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
8010       if (!var) return false;
8011       return considerVariable(var, ref, owner);
8012     }
8013 
8014     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8015       if (member->isArrow()) return false;
8016 
8017       // Don't count this as an indirect ownership.
8018       e = member->getBase();
8019       continue;
8020     }
8021 
8022     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
8023       // Only pay attention to pseudo-objects on property references.
8024       ObjCPropertyRefExpr *pre
8025         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
8026                                               ->IgnoreParens());
8027       if (!pre) return false;
8028       if (pre->isImplicitProperty()) return false;
8029       ObjCPropertyDecl *property = pre->getExplicitProperty();
8030       if (!property->isRetaining() &&
8031           !(property->getPropertyIvarDecl() &&
8032             property->getPropertyIvarDecl()->getType()
8033               .getObjCLifetime() == Qualifiers::OCL_Strong))
8034           return false;
8035 
8036       owner.Indirect = true;
8037       if (pre->isSuperReceiver()) {
8038         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
8039         if (!owner.Variable)
8040           return false;
8041         owner.Loc = pre->getLocation();
8042         owner.Range = pre->getSourceRange();
8043         return true;
8044       }
8045       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
8046                               ->getSourceExpr());
8047       continue;
8048     }
8049 
8050     // Array ivars?
8051 
8052     return false;
8053   }
8054 }
8055 
8056 namespace {
8057   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
8058     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
8059       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
8060         Context(Context), Variable(variable), Capturer(nullptr),
8061         VarWillBeReased(false) {}
8062     ASTContext &Context;
8063     VarDecl *Variable;
8064     Expr *Capturer;
8065     bool VarWillBeReased;
8066 
8067     void VisitDeclRefExpr(DeclRefExpr *ref) {
8068       if (ref->getDecl() == Variable && !Capturer)
8069         Capturer = ref;
8070     }
8071 
8072     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
8073       if (Capturer) return;
8074       Visit(ref->getBase());
8075       if (Capturer && ref->isFreeIvar())
8076         Capturer = ref;
8077     }
8078 
8079     void VisitBlockExpr(BlockExpr *block) {
8080       // Look inside nested blocks
8081       if (block->getBlockDecl()->capturesVariable(Variable))
8082         Visit(block->getBlockDecl()->getBody());
8083     }
8084 
8085     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
8086       if (Capturer) return;
8087       if (OVE->getSourceExpr())
8088         Visit(OVE->getSourceExpr());
8089     }
8090     void VisitBinaryOperator(BinaryOperator *BinOp) {
8091       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
8092         return;
8093       Expr *LHS = BinOp->getLHS();
8094       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8095         if (DRE->getDecl() != Variable)
8096           return;
8097         if (Expr *RHS = BinOp->getRHS()) {
8098           RHS = RHS->IgnoreParenCasts();
8099           llvm::APSInt Value;
8100           VarWillBeReased =
8101             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8102         }
8103       }
8104     }
8105   };
8106 }
8107 
8108 /// Check whether the given argument is a block which captures a
8109 /// variable.
8110 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
8111   assert(owner.Variable && owner.Loc.isValid());
8112 
8113   e = e->IgnoreParenCasts();
8114 
8115   // Look through [^{...} copy] and Block_copy(^{...}).
8116   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
8117     Selector Cmd = ME->getSelector();
8118     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
8119       e = ME->getInstanceReceiver();
8120       if (!e)
8121         return nullptr;
8122       e = e->IgnoreParenCasts();
8123     }
8124   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
8125     if (CE->getNumArgs() == 1) {
8126       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
8127       if (Fn) {
8128         const IdentifierInfo *FnI = Fn->getIdentifier();
8129         if (FnI && FnI->isStr("_Block_copy")) {
8130           e = CE->getArg(0)->IgnoreParenCasts();
8131         }
8132       }
8133     }
8134   }
8135 
8136   BlockExpr *block = dyn_cast<BlockExpr>(e);
8137   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
8138     return nullptr;
8139 
8140   FindCaptureVisitor visitor(S.Context, owner.Variable);
8141   visitor.Visit(block->getBlockDecl()->getBody());
8142   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
8143 }
8144 
8145 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
8146                                 RetainCycleOwner &owner) {
8147   assert(capturer);
8148   assert(owner.Variable && owner.Loc.isValid());
8149 
8150   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
8151     << owner.Variable << capturer->getSourceRange();
8152   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8153     << owner.Indirect << owner.Range;
8154 }
8155 
8156 /// Check for a keyword selector that starts with the word 'add' or
8157 /// 'set'.
8158 static bool isSetterLikeSelector(Selector sel) {
8159   if (sel.isUnarySelector()) return false;
8160 
8161   StringRef str = sel.getNameForSlot(0);
8162   while (!str.empty() && str.front() == '_') str = str.substr(1);
8163   if (str.startswith("set"))
8164     str = str.substr(3);
8165   else if (str.startswith("add")) {
8166     // Specially whitelist 'addOperationWithBlock:'.
8167     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
8168       return false;
8169     str = str.substr(3);
8170   }
8171   else
8172     return false;
8173 
8174   if (str.empty()) return true;
8175   return !isLowercase(str.front());
8176 }
8177 
8178 /// Check a message send to see if it's likely to cause a retain cycle.
8179 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
8180   // Only check instance methods whose selector looks like a setter.
8181   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
8182     return;
8183 
8184   // Try to find a variable that the receiver is strongly owned by.
8185   RetainCycleOwner owner;
8186   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
8187     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
8188       return;
8189   } else {
8190     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
8191     owner.Variable = getCurMethodDecl()->getSelfDecl();
8192     owner.Loc = msg->getSuperLoc();
8193     owner.Range = msg->getSuperLoc();
8194   }
8195 
8196   // Check whether the receiver is captured by any of the arguments.
8197   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
8198     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
8199       return diagnoseRetainCycle(*this, capturer, owner);
8200 }
8201 
8202 /// Check a property assign to see if it's likely to cause a retain cycle.
8203 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
8204   RetainCycleOwner owner;
8205   if (!findRetainCycleOwner(*this, receiver, owner))
8206     return;
8207 
8208   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
8209     diagnoseRetainCycle(*this, capturer, owner);
8210 }
8211 
8212 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
8213   RetainCycleOwner Owner;
8214   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
8215     return;
8216 
8217   // Because we don't have an expression for the variable, we have to set the
8218   // location explicitly here.
8219   Owner.Loc = Var->getLocation();
8220   Owner.Range = Var->getSourceRange();
8221 
8222   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
8223     diagnoseRetainCycle(*this, Capturer, Owner);
8224 }
8225 
8226 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
8227                                      Expr *RHS, bool isProperty) {
8228   // Check if RHS is an Objective-C object literal, which also can get
8229   // immediately zapped in a weak reference.  Note that we explicitly
8230   // allow ObjCStringLiterals, since those are designed to never really die.
8231   RHS = RHS->IgnoreParenImpCasts();
8232 
8233   // This enum needs to match with the 'select' in
8234   // warn_objc_arc_literal_assign (off-by-1).
8235   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
8236   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
8237     return false;
8238 
8239   S.Diag(Loc, diag::warn_arc_literal_assign)
8240     << (unsigned) Kind
8241     << (isProperty ? 0 : 1)
8242     << RHS->getSourceRange();
8243 
8244   return true;
8245 }
8246 
8247 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
8248                                     Qualifiers::ObjCLifetime LT,
8249                                     Expr *RHS, bool isProperty) {
8250   // Strip off any implicit cast added to get to the one ARC-specific.
8251   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8252     if (cast->getCastKind() == CK_ARCConsumeObject) {
8253       S.Diag(Loc, diag::warn_arc_retained_assign)
8254         << (LT == Qualifiers::OCL_ExplicitNone)
8255         << (isProperty ? 0 : 1)
8256         << RHS->getSourceRange();
8257       return true;
8258     }
8259     RHS = cast->getSubExpr();
8260   }
8261 
8262   if (LT == Qualifiers::OCL_Weak &&
8263       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
8264     return true;
8265 
8266   return false;
8267 }
8268 
8269 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
8270                               QualType LHS, Expr *RHS) {
8271   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
8272 
8273   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
8274     return false;
8275 
8276   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
8277     return true;
8278 
8279   return false;
8280 }
8281 
8282 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
8283                               Expr *LHS, Expr *RHS) {
8284   QualType LHSType;
8285   // PropertyRef on LHS type need be directly obtained from
8286   // its declaration as it has a PseudoType.
8287   ObjCPropertyRefExpr *PRE
8288     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
8289   if (PRE && !PRE->isImplicitProperty()) {
8290     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8291     if (PD)
8292       LHSType = PD->getType();
8293   }
8294 
8295   if (LHSType.isNull())
8296     LHSType = LHS->getType();
8297 
8298   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
8299 
8300   if (LT == Qualifiers::OCL_Weak) {
8301     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
8302       getCurFunction()->markSafeWeakUse(LHS);
8303   }
8304 
8305   if (checkUnsafeAssigns(Loc, LHSType, RHS))
8306     return;
8307 
8308   // FIXME. Check for other life times.
8309   if (LT != Qualifiers::OCL_None)
8310     return;
8311 
8312   if (PRE) {
8313     if (PRE->isImplicitProperty())
8314       return;
8315     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
8316     if (!PD)
8317       return;
8318 
8319     unsigned Attributes = PD->getPropertyAttributes();
8320     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
8321       // when 'assign' attribute was not explicitly specified
8322       // by user, ignore it and rely on property type itself
8323       // for lifetime info.
8324       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
8325       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
8326           LHSType->isObjCRetainableType())
8327         return;
8328 
8329       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
8330         if (cast->getCastKind() == CK_ARCConsumeObject) {
8331           Diag(Loc, diag::warn_arc_retained_property_assign)
8332           << RHS->getSourceRange();
8333           return;
8334         }
8335         RHS = cast->getSubExpr();
8336       }
8337     }
8338     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
8339       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
8340         return;
8341     }
8342   }
8343 }
8344 
8345 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
8346 
8347 namespace {
8348 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
8349                                  SourceLocation StmtLoc,
8350                                  const NullStmt *Body) {
8351   // Do not warn if the body is a macro that expands to nothing, e.g:
8352   //
8353   // #define CALL(x)
8354   // if (condition)
8355   //   CALL(0);
8356   //
8357   if (Body->hasLeadingEmptyMacro())
8358     return false;
8359 
8360   // Get line numbers of statement and body.
8361   bool StmtLineInvalid;
8362   unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
8363                                                       &StmtLineInvalid);
8364   if (StmtLineInvalid)
8365     return false;
8366 
8367   bool BodyLineInvalid;
8368   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
8369                                                       &BodyLineInvalid);
8370   if (BodyLineInvalid)
8371     return false;
8372 
8373   // Warn if null statement and body are on the same line.
8374   if (StmtLine != BodyLine)
8375     return false;
8376 
8377   return true;
8378 }
8379 } // Unnamed namespace
8380 
8381 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
8382                                  const Stmt *Body,
8383                                  unsigned DiagID) {
8384   // Since this is a syntactic check, don't emit diagnostic for template
8385   // instantiations, this just adds noise.
8386   if (CurrentInstantiationScope)
8387     return;
8388 
8389   // The body should be a null statement.
8390   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8391   if (!NBody)
8392     return;
8393 
8394   // Do the usual checks.
8395   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8396     return;
8397 
8398   Diag(NBody->getSemiLoc(), DiagID);
8399   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8400 }
8401 
8402 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
8403                                  const Stmt *PossibleBody) {
8404   assert(!CurrentInstantiationScope); // Ensured by caller
8405 
8406   SourceLocation StmtLoc;
8407   const Stmt *Body;
8408   unsigned DiagID;
8409   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
8410     StmtLoc = FS->getRParenLoc();
8411     Body = FS->getBody();
8412     DiagID = diag::warn_empty_for_body;
8413   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
8414     StmtLoc = WS->getCond()->getSourceRange().getEnd();
8415     Body = WS->getBody();
8416     DiagID = diag::warn_empty_while_body;
8417   } else
8418     return; // Neither `for' nor `while'.
8419 
8420   // The body should be a null statement.
8421   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
8422   if (!NBody)
8423     return;
8424 
8425   // Skip expensive checks if diagnostic is disabled.
8426   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
8427     return;
8428 
8429   // Do the usual checks.
8430   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
8431     return;
8432 
8433   // `for(...);' and `while(...);' are popular idioms, so in order to keep
8434   // noise level low, emit diagnostics only if for/while is followed by a
8435   // CompoundStmt, e.g.:
8436   //    for (int i = 0; i < n; i++);
8437   //    {
8438   //      a(i);
8439   //    }
8440   // or if for/while is followed by a statement with more indentation
8441   // than for/while itself:
8442   //    for (int i = 0; i < n; i++);
8443   //      a(i);
8444   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
8445   if (!ProbableTypo) {
8446     bool BodyColInvalid;
8447     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
8448                              PossibleBody->getLocStart(),
8449                              &BodyColInvalid);
8450     if (BodyColInvalid)
8451       return;
8452 
8453     bool StmtColInvalid;
8454     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
8455                              S->getLocStart(),
8456                              &StmtColInvalid);
8457     if (StmtColInvalid)
8458       return;
8459 
8460     if (BodyCol > StmtCol)
8461       ProbableTypo = true;
8462   }
8463 
8464   if (ProbableTypo) {
8465     Diag(NBody->getSemiLoc(), DiagID);
8466     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
8467   }
8468 }
8469 
8470 //===--- CHECK: Warn on self move with std::move. -------------------------===//
8471 
8472 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
8473 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
8474                              SourceLocation OpLoc) {
8475 
8476   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
8477     return;
8478 
8479   if (!ActiveTemplateInstantiations.empty())
8480     return;
8481 
8482   // Strip parens and casts away.
8483   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8484   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8485 
8486   // Check for a call expression
8487   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
8488   if (!CE || CE->getNumArgs() != 1)
8489     return;
8490 
8491   // Check for a call to std::move
8492   const FunctionDecl *FD = CE->getDirectCallee();
8493   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
8494       !FD->getIdentifier()->isStr("move"))
8495     return;
8496 
8497   // Get argument from std::move
8498   RHSExpr = CE->getArg(0);
8499 
8500   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8501   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8502 
8503   // Two DeclRefExpr's, check that the decls are the same.
8504   if (LHSDeclRef && RHSDeclRef) {
8505     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8506       return;
8507     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8508         RHSDeclRef->getDecl()->getCanonicalDecl())
8509       return;
8510 
8511     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8512                                         << LHSExpr->getSourceRange()
8513                                         << RHSExpr->getSourceRange();
8514     return;
8515   }
8516 
8517   // Member variables require a different approach to check for self moves.
8518   // MemberExpr's are the same if every nested MemberExpr refers to the same
8519   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
8520   // the base Expr's are CXXThisExpr's.
8521   const Expr *LHSBase = LHSExpr;
8522   const Expr *RHSBase = RHSExpr;
8523   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
8524   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
8525   if (!LHSME || !RHSME)
8526     return;
8527 
8528   while (LHSME && RHSME) {
8529     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
8530         RHSME->getMemberDecl()->getCanonicalDecl())
8531       return;
8532 
8533     LHSBase = LHSME->getBase();
8534     RHSBase = RHSME->getBase();
8535     LHSME = dyn_cast<MemberExpr>(LHSBase);
8536     RHSME = dyn_cast<MemberExpr>(RHSBase);
8537   }
8538 
8539   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
8540   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
8541   if (LHSDeclRef && RHSDeclRef) {
8542     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
8543       return;
8544     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
8545         RHSDeclRef->getDecl()->getCanonicalDecl())
8546       return;
8547 
8548     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8549                                         << LHSExpr->getSourceRange()
8550                                         << RHSExpr->getSourceRange();
8551     return;
8552   }
8553 
8554   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
8555     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
8556                                         << LHSExpr->getSourceRange()
8557                                         << RHSExpr->getSourceRange();
8558 }
8559 
8560 //===--- Layout compatibility ----------------------------------------------//
8561 
8562 namespace {
8563 
8564 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
8565 
8566 /// \brief Check if two enumeration types are layout-compatible.
8567 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
8568   // C++11 [dcl.enum] p8:
8569   // Two enumeration types are layout-compatible if they have the same
8570   // underlying type.
8571   return ED1->isComplete() && ED2->isComplete() &&
8572          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
8573 }
8574 
8575 /// \brief Check if two fields are layout-compatible.
8576 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
8577   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
8578     return false;
8579 
8580   if (Field1->isBitField() != Field2->isBitField())
8581     return false;
8582 
8583   if (Field1->isBitField()) {
8584     // Make sure that the bit-fields are the same length.
8585     unsigned Bits1 = Field1->getBitWidthValue(C);
8586     unsigned Bits2 = Field2->getBitWidthValue(C);
8587 
8588     if (Bits1 != Bits2)
8589       return false;
8590   }
8591 
8592   return true;
8593 }
8594 
8595 /// \brief Check if two standard-layout structs are layout-compatible.
8596 /// (C++11 [class.mem] p17)
8597 bool isLayoutCompatibleStruct(ASTContext &C,
8598                               RecordDecl *RD1,
8599                               RecordDecl *RD2) {
8600   // If both records are C++ classes, check that base classes match.
8601   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
8602     // If one of records is a CXXRecordDecl we are in C++ mode,
8603     // thus the other one is a CXXRecordDecl, too.
8604     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
8605     // Check number of base classes.
8606     if (D1CXX->getNumBases() != D2CXX->getNumBases())
8607       return false;
8608 
8609     // Check the base classes.
8610     for (CXXRecordDecl::base_class_const_iterator
8611                Base1 = D1CXX->bases_begin(),
8612            BaseEnd1 = D1CXX->bases_end(),
8613               Base2 = D2CXX->bases_begin();
8614          Base1 != BaseEnd1;
8615          ++Base1, ++Base2) {
8616       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
8617         return false;
8618     }
8619   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
8620     // If only RD2 is a C++ class, it should have zero base classes.
8621     if (D2CXX->getNumBases() > 0)
8622       return false;
8623   }
8624 
8625   // Check the fields.
8626   RecordDecl::field_iterator Field2 = RD2->field_begin(),
8627                              Field2End = RD2->field_end(),
8628                              Field1 = RD1->field_begin(),
8629                              Field1End = RD1->field_end();
8630   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
8631     if (!isLayoutCompatible(C, *Field1, *Field2))
8632       return false;
8633   }
8634   if (Field1 != Field1End || Field2 != Field2End)
8635     return false;
8636 
8637   return true;
8638 }
8639 
8640 /// \brief Check if two standard-layout unions are layout-compatible.
8641 /// (C++11 [class.mem] p18)
8642 bool isLayoutCompatibleUnion(ASTContext &C,
8643                              RecordDecl *RD1,
8644                              RecordDecl *RD2) {
8645   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
8646   for (auto *Field2 : RD2->fields())
8647     UnmatchedFields.insert(Field2);
8648 
8649   for (auto *Field1 : RD1->fields()) {
8650     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
8651         I = UnmatchedFields.begin(),
8652         E = UnmatchedFields.end();
8653 
8654     for ( ; I != E; ++I) {
8655       if (isLayoutCompatible(C, Field1, *I)) {
8656         bool Result = UnmatchedFields.erase(*I);
8657         (void) Result;
8658         assert(Result);
8659         break;
8660       }
8661     }
8662     if (I == E)
8663       return false;
8664   }
8665 
8666   return UnmatchedFields.empty();
8667 }
8668 
8669 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
8670   if (RD1->isUnion() != RD2->isUnion())
8671     return false;
8672 
8673   if (RD1->isUnion())
8674     return isLayoutCompatibleUnion(C, RD1, RD2);
8675   else
8676     return isLayoutCompatibleStruct(C, RD1, RD2);
8677 }
8678 
8679 /// \brief Check if two types are layout-compatible in C++11 sense.
8680 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
8681   if (T1.isNull() || T2.isNull())
8682     return false;
8683 
8684   // C++11 [basic.types] p11:
8685   // If two types T1 and T2 are the same type, then T1 and T2 are
8686   // layout-compatible types.
8687   if (C.hasSameType(T1, T2))
8688     return true;
8689 
8690   T1 = T1.getCanonicalType().getUnqualifiedType();
8691   T2 = T2.getCanonicalType().getUnqualifiedType();
8692 
8693   const Type::TypeClass TC1 = T1->getTypeClass();
8694   const Type::TypeClass TC2 = T2->getTypeClass();
8695 
8696   if (TC1 != TC2)
8697     return false;
8698 
8699   if (TC1 == Type::Enum) {
8700     return isLayoutCompatible(C,
8701                               cast<EnumType>(T1)->getDecl(),
8702                               cast<EnumType>(T2)->getDecl());
8703   } else if (TC1 == Type::Record) {
8704     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
8705       return false;
8706 
8707     return isLayoutCompatible(C,
8708                               cast<RecordType>(T1)->getDecl(),
8709                               cast<RecordType>(T2)->getDecl());
8710   }
8711 
8712   return false;
8713 }
8714 }
8715 
8716 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
8717 
8718 namespace {
8719 /// \brief Given a type tag expression find the type tag itself.
8720 ///
8721 /// \param TypeExpr Type tag expression, as it appears in user's code.
8722 ///
8723 /// \param VD Declaration of an identifier that appears in a type tag.
8724 ///
8725 /// \param MagicValue Type tag magic value.
8726 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
8727                      const ValueDecl **VD, uint64_t *MagicValue) {
8728   while(true) {
8729     if (!TypeExpr)
8730       return false;
8731 
8732     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
8733 
8734     switch (TypeExpr->getStmtClass()) {
8735     case Stmt::UnaryOperatorClass: {
8736       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
8737       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
8738         TypeExpr = UO->getSubExpr();
8739         continue;
8740       }
8741       return false;
8742     }
8743 
8744     case Stmt::DeclRefExprClass: {
8745       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
8746       *VD = DRE->getDecl();
8747       return true;
8748     }
8749 
8750     case Stmt::IntegerLiteralClass: {
8751       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
8752       llvm::APInt MagicValueAPInt = IL->getValue();
8753       if (MagicValueAPInt.getActiveBits() <= 64) {
8754         *MagicValue = MagicValueAPInt.getZExtValue();
8755         return true;
8756       } else
8757         return false;
8758     }
8759 
8760     case Stmt::BinaryConditionalOperatorClass:
8761     case Stmt::ConditionalOperatorClass: {
8762       const AbstractConditionalOperator *ACO =
8763           cast<AbstractConditionalOperator>(TypeExpr);
8764       bool Result;
8765       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
8766         if (Result)
8767           TypeExpr = ACO->getTrueExpr();
8768         else
8769           TypeExpr = ACO->getFalseExpr();
8770         continue;
8771       }
8772       return false;
8773     }
8774 
8775     case Stmt::BinaryOperatorClass: {
8776       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
8777       if (BO->getOpcode() == BO_Comma) {
8778         TypeExpr = BO->getRHS();
8779         continue;
8780       }
8781       return false;
8782     }
8783 
8784     default:
8785       return false;
8786     }
8787   }
8788 }
8789 
8790 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
8791 ///
8792 /// \param TypeExpr Expression that specifies a type tag.
8793 ///
8794 /// \param MagicValues Registered magic values.
8795 ///
8796 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
8797 ///        kind.
8798 ///
8799 /// \param TypeInfo Information about the corresponding C type.
8800 ///
8801 /// \returns true if the corresponding C type was found.
8802 bool GetMatchingCType(
8803         const IdentifierInfo *ArgumentKind,
8804         const Expr *TypeExpr, const ASTContext &Ctx,
8805         const llvm::DenseMap<Sema::TypeTagMagicValue,
8806                              Sema::TypeTagData> *MagicValues,
8807         bool &FoundWrongKind,
8808         Sema::TypeTagData &TypeInfo) {
8809   FoundWrongKind = false;
8810 
8811   // Variable declaration that has type_tag_for_datatype attribute.
8812   const ValueDecl *VD = nullptr;
8813 
8814   uint64_t MagicValue;
8815 
8816   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
8817     return false;
8818 
8819   if (VD) {
8820     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
8821       if (I->getArgumentKind() != ArgumentKind) {
8822         FoundWrongKind = true;
8823         return false;
8824       }
8825       TypeInfo.Type = I->getMatchingCType();
8826       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
8827       TypeInfo.MustBeNull = I->getMustBeNull();
8828       return true;
8829     }
8830     return false;
8831   }
8832 
8833   if (!MagicValues)
8834     return false;
8835 
8836   llvm::DenseMap<Sema::TypeTagMagicValue,
8837                  Sema::TypeTagData>::const_iterator I =
8838       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
8839   if (I == MagicValues->end())
8840     return false;
8841 
8842   TypeInfo = I->second;
8843   return true;
8844 }
8845 } // unnamed namespace
8846 
8847 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
8848                                       uint64_t MagicValue, QualType Type,
8849                                       bool LayoutCompatible,
8850                                       bool MustBeNull) {
8851   if (!TypeTagForDatatypeMagicValues)
8852     TypeTagForDatatypeMagicValues.reset(
8853         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
8854 
8855   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
8856   (*TypeTagForDatatypeMagicValues)[Magic] =
8857       TypeTagData(Type, LayoutCompatible, MustBeNull);
8858 }
8859 
8860 namespace {
8861 bool IsSameCharType(QualType T1, QualType T2) {
8862   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
8863   if (!BT1)
8864     return false;
8865 
8866   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
8867   if (!BT2)
8868     return false;
8869 
8870   BuiltinType::Kind T1Kind = BT1->getKind();
8871   BuiltinType::Kind T2Kind = BT2->getKind();
8872 
8873   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
8874          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
8875          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
8876          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
8877 }
8878 } // unnamed namespace
8879 
8880 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
8881                                     const Expr * const *ExprArgs) {
8882   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
8883   bool IsPointerAttr = Attr->getIsPointer();
8884 
8885   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
8886   bool FoundWrongKind;
8887   TypeTagData TypeInfo;
8888   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
8889                         TypeTagForDatatypeMagicValues.get(),
8890                         FoundWrongKind, TypeInfo)) {
8891     if (FoundWrongKind)
8892       Diag(TypeTagExpr->getExprLoc(),
8893            diag::warn_type_tag_for_datatype_wrong_kind)
8894         << TypeTagExpr->getSourceRange();
8895     return;
8896   }
8897 
8898   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
8899   if (IsPointerAttr) {
8900     // Skip implicit cast of pointer to `void *' (as a function argument).
8901     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
8902       if (ICE->getType()->isVoidPointerType() &&
8903           ICE->getCastKind() == CK_BitCast)
8904         ArgumentExpr = ICE->getSubExpr();
8905   }
8906   QualType ArgumentType = ArgumentExpr->getType();
8907 
8908   // Passing a `void*' pointer shouldn't trigger a warning.
8909   if (IsPointerAttr && ArgumentType->isVoidPointerType())
8910     return;
8911 
8912   if (TypeInfo.MustBeNull) {
8913     // Type tag with matching void type requires a null pointer.
8914     if (!ArgumentExpr->isNullPointerConstant(Context,
8915                                              Expr::NPC_ValueDependentIsNotNull)) {
8916       Diag(ArgumentExpr->getExprLoc(),
8917            diag::warn_type_safety_null_pointer_required)
8918           << ArgumentKind->getName()
8919           << ArgumentExpr->getSourceRange()
8920           << TypeTagExpr->getSourceRange();
8921     }
8922     return;
8923   }
8924 
8925   QualType RequiredType = TypeInfo.Type;
8926   if (IsPointerAttr)
8927     RequiredType = Context.getPointerType(RequiredType);
8928 
8929   bool mismatch = false;
8930   if (!TypeInfo.LayoutCompatible) {
8931     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
8932 
8933     // C++11 [basic.fundamental] p1:
8934     // Plain char, signed char, and unsigned char are three distinct types.
8935     //
8936     // But we treat plain `char' as equivalent to `signed char' or `unsigned
8937     // char' depending on the current char signedness mode.
8938     if (mismatch)
8939       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
8940                                            RequiredType->getPointeeType())) ||
8941           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
8942         mismatch = false;
8943   } else
8944     if (IsPointerAttr)
8945       mismatch = !isLayoutCompatible(Context,
8946                                      ArgumentType->getPointeeType(),
8947                                      RequiredType->getPointeeType());
8948     else
8949       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
8950 
8951   if (mismatch)
8952     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
8953         << ArgumentType << ArgumentKind
8954         << TypeInfo.LayoutCompatible << RequiredType
8955         << ArgumentExpr->getSourceRange()
8956         << TypeTagExpr->getSourceRange();
8957 }
8958 
8959