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