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/Initialization.h"
16 #include "clang/Sema/Sema.h"
17 #include "clang/Sema/SemaInternal.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/Analysis/Analyses/FormatString.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/EvaluatedExprVisitor.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/StmtObjC.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "clang/Basic/TargetBuiltins.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Basic/ConvertUTF.h"
39 #include <limits>
40 using namespace clang;
41 using namespace sema;
42 
43 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
44                                                     unsigned ByteNo) const {
45   return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
46                                PP.getLangOptions(), PP.getTargetInfo());
47 }
48 
49 /// Checks that a call expression's argument count is the desired number.
50 /// This is useful when doing custom type-checking.  Returns true on error.
51 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
52   unsigned argCount = call->getNumArgs();
53   if (argCount == desiredArgCount) return false;
54 
55   if (argCount < desiredArgCount)
56     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
57         << 0 /*function call*/ << desiredArgCount << argCount
58         << call->getSourceRange();
59 
60   // Highlight all the excess arguments.
61   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
62                     call->getArg(argCount - 1)->getLocEnd());
63 
64   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
65     << 0 /*function call*/ << desiredArgCount << argCount
66     << call->getArg(1)->getSourceRange();
67 }
68 
69 /// CheckBuiltinAnnotationString - Checks that string argument to the builtin
70 /// annotation is a non wide string literal.
71 static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
72   Arg = Arg->IgnoreParenCasts();
73   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
74   if (!Literal || !Literal->isAscii()) {
75     S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
76       << Arg->getSourceRange();
77     return true;
78   }
79   return false;
80 }
81 
82 ExprResult
83 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
84   ExprResult TheCallResult(Owned(TheCall));
85 
86   // Find out if any arguments are required to be integer constant expressions.
87   unsigned ICEArguments = 0;
88   ASTContext::GetBuiltinTypeError Error;
89   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
90   if (Error != ASTContext::GE_None)
91     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
92 
93   // If any arguments are required to be ICE's, check and diagnose.
94   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
95     // Skip arguments not required to be ICE's.
96     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
97 
98     llvm::APSInt Result;
99     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
100       return true;
101     ICEArguments &= ~(1 << ArgNo);
102   }
103 
104   switch (BuiltinID) {
105   case Builtin::BI__builtin___CFStringMakeConstantString:
106     assert(TheCall->getNumArgs() == 1 &&
107            "Wrong # arguments to builtin CFStringMakeConstantString");
108     if (CheckObjCString(TheCall->getArg(0)))
109       return ExprError();
110     break;
111   case Builtin::BI__builtin_stdarg_start:
112   case Builtin::BI__builtin_va_start:
113     if (SemaBuiltinVAStart(TheCall))
114       return ExprError();
115     break;
116   case Builtin::BI__builtin_isgreater:
117   case Builtin::BI__builtin_isgreaterequal:
118   case Builtin::BI__builtin_isless:
119   case Builtin::BI__builtin_islessequal:
120   case Builtin::BI__builtin_islessgreater:
121   case Builtin::BI__builtin_isunordered:
122     if (SemaBuiltinUnorderedCompare(TheCall))
123       return ExprError();
124     break;
125   case Builtin::BI__builtin_fpclassify:
126     if (SemaBuiltinFPClassification(TheCall, 6))
127       return ExprError();
128     break;
129   case Builtin::BI__builtin_isfinite:
130   case Builtin::BI__builtin_isinf:
131   case Builtin::BI__builtin_isinf_sign:
132   case Builtin::BI__builtin_isnan:
133   case Builtin::BI__builtin_isnormal:
134     if (SemaBuiltinFPClassification(TheCall, 1))
135       return ExprError();
136     break;
137   case Builtin::BI__builtin_shufflevector:
138     return SemaBuiltinShuffleVector(TheCall);
139     // TheCall will be freed by the smart pointer here, but that's fine, since
140     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
141   case Builtin::BI__builtin_prefetch:
142     if (SemaBuiltinPrefetch(TheCall))
143       return ExprError();
144     break;
145   case Builtin::BI__builtin_object_size:
146     if (SemaBuiltinObjectSize(TheCall))
147       return ExprError();
148     break;
149   case Builtin::BI__builtin_longjmp:
150     if (SemaBuiltinLongjmp(TheCall))
151       return ExprError();
152     break;
153 
154   case Builtin::BI__builtin_classify_type:
155     if (checkArgCount(*this, TheCall, 1)) return true;
156     TheCall->setType(Context.IntTy);
157     break;
158   case Builtin::BI__builtin_constant_p:
159     if (checkArgCount(*this, TheCall, 1)) return true;
160     TheCall->setType(Context.IntTy);
161     break;
162   case Builtin::BI__sync_fetch_and_add:
163   case Builtin::BI__sync_fetch_and_add_1:
164   case Builtin::BI__sync_fetch_and_add_2:
165   case Builtin::BI__sync_fetch_and_add_4:
166   case Builtin::BI__sync_fetch_and_add_8:
167   case Builtin::BI__sync_fetch_and_add_16:
168   case Builtin::BI__sync_fetch_and_sub:
169   case Builtin::BI__sync_fetch_and_sub_1:
170   case Builtin::BI__sync_fetch_and_sub_2:
171   case Builtin::BI__sync_fetch_and_sub_4:
172   case Builtin::BI__sync_fetch_and_sub_8:
173   case Builtin::BI__sync_fetch_and_sub_16:
174   case Builtin::BI__sync_fetch_and_or:
175   case Builtin::BI__sync_fetch_and_or_1:
176   case Builtin::BI__sync_fetch_and_or_2:
177   case Builtin::BI__sync_fetch_and_or_4:
178   case Builtin::BI__sync_fetch_and_or_8:
179   case Builtin::BI__sync_fetch_and_or_16:
180   case Builtin::BI__sync_fetch_and_and:
181   case Builtin::BI__sync_fetch_and_and_1:
182   case Builtin::BI__sync_fetch_and_and_2:
183   case Builtin::BI__sync_fetch_and_and_4:
184   case Builtin::BI__sync_fetch_and_and_8:
185   case Builtin::BI__sync_fetch_and_and_16:
186   case Builtin::BI__sync_fetch_and_xor:
187   case Builtin::BI__sync_fetch_and_xor_1:
188   case Builtin::BI__sync_fetch_and_xor_2:
189   case Builtin::BI__sync_fetch_and_xor_4:
190   case Builtin::BI__sync_fetch_and_xor_8:
191   case Builtin::BI__sync_fetch_and_xor_16:
192   case Builtin::BI__sync_add_and_fetch:
193   case Builtin::BI__sync_add_and_fetch_1:
194   case Builtin::BI__sync_add_and_fetch_2:
195   case Builtin::BI__sync_add_and_fetch_4:
196   case Builtin::BI__sync_add_and_fetch_8:
197   case Builtin::BI__sync_add_and_fetch_16:
198   case Builtin::BI__sync_sub_and_fetch:
199   case Builtin::BI__sync_sub_and_fetch_1:
200   case Builtin::BI__sync_sub_and_fetch_2:
201   case Builtin::BI__sync_sub_and_fetch_4:
202   case Builtin::BI__sync_sub_and_fetch_8:
203   case Builtin::BI__sync_sub_and_fetch_16:
204   case Builtin::BI__sync_and_and_fetch:
205   case Builtin::BI__sync_and_and_fetch_1:
206   case Builtin::BI__sync_and_and_fetch_2:
207   case Builtin::BI__sync_and_and_fetch_4:
208   case Builtin::BI__sync_and_and_fetch_8:
209   case Builtin::BI__sync_and_and_fetch_16:
210   case Builtin::BI__sync_or_and_fetch:
211   case Builtin::BI__sync_or_and_fetch_1:
212   case Builtin::BI__sync_or_and_fetch_2:
213   case Builtin::BI__sync_or_and_fetch_4:
214   case Builtin::BI__sync_or_and_fetch_8:
215   case Builtin::BI__sync_or_and_fetch_16:
216   case Builtin::BI__sync_xor_and_fetch:
217   case Builtin::BI__sync_xor_and_fetch_1:
218   case Builtin::BI__sync_xor_and_fetch_2:
219   case Builtin::BI__sync_xor_and_fetch_4:
220   case Builtin::BI__sync_xor_and_fetch_8:
221   case Builtin::BI__sync_xor_and_fetch_16:
222   case Builtin::BI__sync_val_compare_and_swap:
223   case Builtin::BI__sync_val_compare_and_swap_1:
224   case Builtin::BI__sync_val_compare_and_swap_2:
225   case Builtin::BI__sync_val_compare_and_swap_4:
226   case Builtin::BI__sync_val_compare_and_swap_8:
227   case Builtin::BI__sync_val_compare_and_swap_16:
228   case Builtin::BI__sync_bool_compare_and_swap:
229   case Builtin::BI__sync_bool_compare_and_swap_1:
230   case Builtin::BI__sync_bool_compare_and_swap_2:
231   case Builtin::BI__sync_bool_compare_and_swap_4:
232   case Builtin::BI__sync_bool_compare_and_swap_8:
233   case Builtin::BI__sync_bool_compare_and_swap_16:
234   case Builtin::BI__sync_lock_test_and_set:
235   case Builtin::BI__sync_lock_test_and_set_1:
236   case Builtin::BI__sync_lock_test_and_set_2:
237   case Builtin::BI__sync_lock_test_and_set_4:
238   case Builtin::BI__sync_lock_test_and_set_8:
239   case Builtin::BI__sync_lock_test_and_set_16:
240   case Builtin::BI__sync_lock_release:
241   case Builtin::BI__sync_lock_release_1:
242   case Builtin::BI__sync_lock_release_2:
243   case Builtin::BI__sync_lock_release_4:
244   case Builtin::BI__sync_lock_release_8:
245   case Builtin::BI__sync_lock_release_16:
246   case Builtin::BI__sync_swap:
247   case Builtin::BI__sync_swap_1:
248   case Builtin::BI__sync_swap_2:
249   case Builtin::BI__sync_swap_4:
250   case Builtin::BI__sync_swap_8:
251   case Builtin::BI__sync_swap_16:
252     return SemaBuiltinAtomicOverloaded(move(TheCallResult));
253   case Builtin::BI__atomic_load:
254     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
255   case Builtin::BI__atomic_store:
256     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
257   case Builtin::BI__atomic_init:
258     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init);
259   case Builtin::BI__atomic_exchange:
260     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
261   case Builtin::BI__atomic_compare_exchange_strong:
262     return SemaAtomicOpsOverloaded(move(TheCallResult),
263                                    AtomicExpr::CmpXchgStrong);
264   case Builtin::BI__atomic_compare_exchange_weak:
265     return SemaAtomicOpsOverloaded(move(TheCallResult),
266                                    AtomicExpr::CmpXchgWeak);
267   case Builtin::BI__atomic_fetch_add:
268     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
269   case Builtin::BI__atomic_fetch_sub:
270     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
271   case Builtin::BI__atomic_fetch_and:
272     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
273   case Builtin::BI__atomic_fetch_or:
274     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
275   case Builtin::BI__atomic_fetch_xor:
276     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
277   case Builtin::BI__builtin_annotation:
278     if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
279       return ExprError();
280     break;
281   }
282 
283   // Since the target specific builtins for each arch overlap, only check those
284   // of the arch we are compiling for.
285   if (BuiltinID >= Builtin::FirstTSBuiltin) {
286     switch (Context.getTargetInfo().getTriple().getArch()) {
287       case llvm::Triple::arm:
288       case llvm::Triple::thumb:
289         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
290           return ExprError();
291         break;
292       default:
293         break;
294     }
295   }
296 
297   return move(TheCallResult);
298 }
299 
300 // Get the valid immediate range for the specified NEON type code.
301 static unsigned RFT(unsigned t, bool shift = false) {
302   NeonTypeFlags Type(t);
303   int IsQuad = Type.isQuad();
304   switch (Type.getEltType()) {
305   case NeonTypeFlags::Int8:
306   case NeonTypeFlags::Poly8:
307     return shift ? 7 : (8 << IsQuad) - 1;
308   case NeonTypeFlags::Int16:
309   case NeonTypeFlags::Poly16:
310     return shift ? 15 : (4 << IsQuad) - 1;
311   case NeonTypeFlags::Int32:
312     return shift ? 31 : (2 << IsQuad) - 1;
313   case NeonTypeFlags::Int64:
314     return shift ? 63 : (1 << IsQuad) - 1;
315   case NeonTypeFlags::Float16:
316     assert(!shift && "cannot shift float types!");
317     return (4 << IsQuad) - 1;
318   case NeonTypeFlags::Float32:
319     assert(!shift && "cannot shift float types!");
320     return (2 << IsQuad) - 1;
321   }
322   llvm_unreachable("Invalid NeonTypeFlag!");
323 }
324 
325 /// getNeonEltType - Return the QualType corresponding to the elements of
326 /// the vector type specified by the NeonTypeFlags.  This is used to check
327 /// the pointer arguments for Neon load/store intrinsics.
328 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
329   switch (Flags.getEltType()) {
330   case NeonTypeFlags::Int8:
331     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
332   case NeonTypeFlags::Int16:
333     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
334   case NeonTypeFlags::Int32:
335     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
336   case NeonTypeFlags::Int64:
337     return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
338   case NeonTypeFlags::Poly8:
339     return Context.SignedCharTy;
340   case NeonTypeFlags::Poly16:
341     return Context.ShortTy;
342   case NeonTypeFlags::Float16:
343     return Context.UnsignedShortTy;
344   case NeonTypeFlags::Float32:
345     return Context.FloatTy;
346   }
347   llvm_unreachable("Invalid NeonTypeFlag!");
348 }
349 
350 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
351   llvm::APSInt Result;
352 
353   unsigned mask = 0;
354   unsigned TV = 0;
355   int PtrArgNum = -1;
356   bool HasConstPtr = false;
357   switch (BuiltinID) {
358 #define GET_NEON_OVERLOAD_CHECK
359 #include "clang/Basic/arm_neon.inc"
360 #undef GET_NEON_OVERLOAD_CHECK
361   }
362 
363   // For NEON intrinsics which are overloaded on vector element type, validate
364   // the immediate which specifies which variant to emit.
365   unsigned ImmArg = TheCall->getNumArgs()-1;
366   if (mask) {
367     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
368       return true;
369 
370     TV = Result.getLimitedValue(64);
371     if ((TV > 63) || (mask & (1 << TV)) == 0)
372       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
373         << TheCall->getArg(ImmArg)->getSourceRange();
374   }
375 
376   if (PtrArgNum >= 0) {
377     // Check that pointer arguments have the specified type.
378     Expr *Arg = TheCall->getArg(PtrArgNum);
379     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
380       Arg = ICE->getSubExpr();
381     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
382     QualType RHSTy = RHS.get()->getType();
383     QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
384     if (HasConstPtr)
385       EltTy = EltTy.withConst();
386     QualType LHSTy = Context.getPointerType(EltTy);
387     AssignConvertType ConvTy;
388     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
389     if (RHS.isInvalid())
390       return true;
391     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
392                                  RHS.get(), AA_Assigning))
393       return true;
394   }
395 
396   // For NEON intrinsics which take an immediate value as part of the
397   // instruction, range check them here.
398   unsigned i = 0, l = 0, u = 0;
399   switch (BuiltinID) {
400   default: return false;
401   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
402   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
403   case ARM::BI__builtin_arm_vcvtr_f:
404   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
405 #define GET_NEON_IMMEDIATE_CHECK
406 #include "clang/Basic/arm_neon.inc"
407 #undef GET_NEON_IMMEDIATE_CHECK
408   };
409 
410   // Check that the immediate argument is actually a constant.
411   if (SemaBuiltinConstantArg(TheCall, i, Result))
412     return true;
413 
414   // Range check against the upper/lower values for this isntruction.
415   unsigned Val = Result.getZExtValue();
416   if (Val < l || Val > (u + l))
417     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
418       << l << u+l << TheCall->getArg(i)->getSourceRange();
419 
420   // FIXME: VFP Intrinsics should error if VFP not present.
421   return false;
422 }
423 
424 /// CheckFunctionCall - Check a direct function call for various correctness
425 /// and safety properties not strictly enforced by the C type system.
426 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
427   // Get the IdentifierInfo* for the called function.
428   IdentifierInfo *FnInfo = FDecl->getIdentifier();
429 
430   // None of the checks below are needed for functions that don't have
431   // simple names (e.g., C++ conversion functions).
432   if (!FnInfo)
433     return false;
434 
435   // FIXME: This mechanism should be abstracted to be less fragile and
436   // more efficient. For example, just map function ids to custom
437   // handlers.
438 
439   // Printf and scanf checking.
440   for (specific_attr_iterator<FormatAttr>
441          i = FDecl->specific_attr_begin<FormatAttr>(),
442          e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
443     CheckFormatArguments(*i, TheCall);
444   }
445 
446   for (specific_attr_iterator<NonNullAttr>
447          i = FDecl->specific_attr_begin<NonNullAttr>(),
448          e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
449     CheckNonNullArguments(*i, TheCall->getArgs(),
450                           TheCall->getCallee()->getLocStart());
451   }
452 
453   unsigned CMId = FDecl->getMemoryFunctionKind();
454   if (CMId == 0)
455     return false;
456 
457   // Handle memory setting and copying functions.
458   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
459     CheckStrlcpycatArguments(TheCall, FnInfo);
460   else if (CMId == Builtin::BIstrncat)
461     CheckStrncatArguments(TheCall, FnInfo);
462   else
463     CheckMemaccessArguments(TheCall, CMId, FnInfo);
464 
465   return false;
466 }
467 
468 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
469                                Expr **Args, unsigned NumArgs) {
470   for (specific_attr_iterator<FormatAttr>
471        i = Method->specific_attr_begin<FormatAttr>(),
472        e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
473 
474     CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
475                          Method->getSourceRange());
476   }
477 
478   // diagnose nonnull arguments.
479   for (specific_attr_iterator<NonNullAttr>
480        i = Method->specific_attr_begin<NonNullAttr>(),
481        e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
482     CheckNonNullArguments(*i, Args, lbrac);
483   }
484 
485   return false;
486 }
487 
488 bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
489   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
490   if (!V)
491     return false;
492 
493   QualType Ty = V->getType();
494   if (!Ty->isBlockPointerType())
495     return false;
496 
497   // format string checking.
498   for (specific_attr_iterator<FormatAttr>
499        i = NDecl->specific_attr_begin<FormatAttr>(),
500        e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
501     CheckFormatArguments(*i, TheCall);
502   }
503 
504   return false;
505 }
506 
507 ExprResult
508 Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
509   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
510   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
511 
512   // All these operations take one of the following four forms:
513   // T   __atomic_load(_Atomic(T)*, int)                              (loads)
514   // T*  __atomic_add(_Atomic(T*)*, ptrdiff_t, int)         (pointer add/sub)
515   // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
516   //                                                                (cmpxchg)
517   // T   __atomic_exchange(_Atomic(T)*, T, int)             (everything else)
518   // where T is an appropriate type, and the int paremeterss are for orderings.
519   unsigned NumVals = 1;
520   unsigned NumOrders = 1;
521   if (Op == AtomicExpr::Load) {
522     NumVals = 0;
523   } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
524     NumVals = 2;
525     NumOrders = 2;
526   }
527   if (Op == AtomicExpr::Init)
528     NumOrders = 0;
529 
530   if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
531     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
532       << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
533       << TheCall->getCallee()->getSourceRange();
534     return ExprError();
535   } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
536     Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
537          diag::err_typecheck_call_too_many_args)
538       << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
539       << TheCall->getCallee()->getSourceRange();
540     return ExprError();
541   }
542 
543   // Inspect the first argument of the atomic operation.  This should always be
544   // a pointer to an _Atomic type.
545   Expr *Ptr = TheCall->getArg(0);
546   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
547   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
548   if (!pointerType) {
549     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
550       << Ptr->getType() << Ptr->getSourceRange();
551     return ExprError();
552   }
553 
554   QualType AtomTy = pointerType->getPointeeType();
555   if (!AtomTy->isAtomicType()) {
556     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
557       << Ptr->getType() << Ptr->getSourceRange();
558     return ExprError();
559   }
560   QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
561 
562   if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
563       !ValType->isIntegerType() && !ValType->isPointerType()) {
564     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
565       << Ptr->getType() << Ptr->getSourceRange();
566     return ExprError();
567   }
568 
569   if (!ValType->isIntegerType() &&
570       (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
571     Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
572       << Ptr->getType() << Ptr->getSourceRange();
573     return ExprError();
574   }
575 
576   switch (ValType.getObjCLifetime()) {
577   case Qualifiers::OCL_None:
578   case Qualifiers::OCL_ExplicitNone:
579     // okay
580     break;
581 
582   case Qualifiers::OCL_Weak:
583   case Qualifiers::OCL_Strong:
584   case Qualifiers::OCL_Autoreleasing:
585     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
586       << ValType << Ptr->getSourceRange();
587     return ExprError();
588   }
589 
590   QualType ResultType = ValType;
591   if (Op == AtomicExpr::Store || Op == AtomicExpr::Init)
592     ResultType = Context.VoidTy;
593   else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
594     ResultType = Context.BoolTy;
595 
596   // The first argument --- the pointer --- has a fixed type; we
597   // deduce the types of the rest of the arguments accordingly.  Walk
598   // the remaining arguments, converting them to the deduced value type.
599   for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
600     ExprResult Arg = TheCall->getArg(i);
601     QualType Ty;
602     if (i < NumVals+1) {
603       // The second argument to a cmpxchg is a pointer to the data which will
604       // be exchanged. The second argument to a pointer add/subtract is the
605       // amount to add/subtract, which must be a ptrdiff_t.  The third
606       // argument to a cmpxchg and the second argument in all other cases
607       // is the type of the value.
608       if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
609                      Op == AtomicExpr::CmpXchgStrong))
610          Ty = Context.getPointerType(ValType.getUnqualifiedType());
611       else if (!ValType->isIntegerType() &&
612                (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
613         Ty = Context.getPointerDiffType();
614       else
615         Ty = ValType;
616     } else {
617       // The order(s) are always converted to int.
618       Ty = Context.IntTy;
619     }
620     InitializedEntity Entity =
621         InitializedEntity::InitializeParameter(Context, Ty, false);
622     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
623     if (Arg.isInvalid())
624       return true;
625     TheCall->setArg(i, Arg.get());
626   }
627 
628   SmallVector<Expr*, 5> SubExprs;
629   SubExprs.push_back(Ptr);
630   if (Op == AtomicExpr::Load) {
631     SubExprs.push_back(TheCall->getArg(1)); // Order
632   } else if (Op == AtomicExpr::Init) {
633     SubExprs.push_back(TheCall->getArg(1)); // Val1
634   } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
635     SubExprs.push_back(TheCall->getArg(2)); // Order
636     SubExprs.push_back(TheCall->getArg(1)); // Val1
637   } else {
638     SubExprs.push_back(TheCall->getArg(3)); // Order
639     SubExprs.push_back(TheCall->getArg(1)); // Val1
640     SubExprs.push_back(TheCall->getArg(2)); // Val2
641     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
642   }
643 
644   return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
645                                         SubExprs.data(), SubExprs.size(),
646                                         ResultType, Op,
647                                         TheCall->getRParenLoc()));
648 }
649 
650 
651 /// checkBuiltinArgument - Given a call to a builtin function, perform
652 /// normal type-checking on the given argument, updating the call in
653 /// place.  This is useful when a builtin function requires custom
654 /// type-checking for some of its arguments but not necessarily all of
655 /// them.
656 ///
657 /// Returns true on error.
658 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
659   FunctionDecl *Fn = E->getDirectCallee();
660   assert(Fn && "builtin call without direct callee!");
661 
662   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
663   InitializedEntity Entity =
664     InitializedEntity::InitializeParameter(S.Context, Param);
665 
666   ExprResult Arg = E->getArg(0);
667   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
668   if (Arg.isInvalid())
669     return true;
670 
671   E->setArg(ArgIndex, Arg.take());
672   return false;
673 }
674 
675 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
676 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
677 /// type of its first argument.  The main ActOnCallExpr routines have already
678 /// promoted the types of arguments because all of these calls are prototyped as
679 /// void(...).
680 ///
681 /// This function goes through and does final semantic checking for these
682 /// builtins,
683 ExprResult
684 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
685   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
686   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
687   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
688 
689   // Ensure that we have at least one argument to do type inference from.
690   if (TheCall->getNumArgs() < 1) {
691     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
692       << 0 << 1 << TheCall->getNumArgs()
693       << TheCall->getCallee()->getSourceRange();
694     return ExprError();
695   }
696 
697   // Inspect the first argument of the atomic builtin.  This should always be
698   // a pointer type, whose element is an integral scalar or pointer type.
699   // Because it is a pointer type, we don't have to worry about any implicit
700   // casts here.
701   // FIXME: We don't allow floating point scalars as input.
702   Expr *FirstArg = TheCall->getArg(0);
703   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
704   if (FirstArgResult.isInvalid())
705     return ExprError();
706   FirstArg = FirstArgResult.take();
707   TheCall->setArg(0, FirstArg);
708 
709   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
710   if (!pointerType) {
711     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
712       << FirstArg->getType() << FirstArg->getSourceRange();
713     return ExprError();
714   }
715 
716   QualType ValType = pointerType->getPointeeType();
717   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
718       !ValType->isBlockPointerType()) {
719     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
720       << FirstArg->getType() << FirstArg->getSourceRange();
721     return ExprError();
722   }
723 
724   switch (ValType.getObjCLifetime()) {
725   case Qualifiers::OCL_None:
726   case Qualifiers::OCL_ExplicitNone:
727     // okay
728     break;
729 
730   case Qualifiers::OCL_Weak:
731   case Qualifiers::OCL_Strong:
732   case Qualifiers::OCL_Autoreleasing:
733     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
734       << ValType << FirstArg->getSourceRange();
735     return ExprError();
736   }
737 
738   // Strip any qualifiers off ValType.
739   ValType = ValType.getUnqualifiedType();
740 
741   // The majority of builtins return a value, but a few have special return
742   // types, so allow them to override appropriately below.
743   QualType ResultType = ValType;
744 
745   // We need to figure out which concrete builtin this maps onto.  For example,
746   // __sync_fetch_and_add with a 2 byte object turns into
747   // __sync_fetch_and_add_2.
748 #define BUILTIN_ROW(x) \
749   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
750     Builtin::BI##x##_8, Builtin::BI##x##_16 }
751 
752   static const unsigned BuiltinIndices[][5] = {
753     BUILTIN_ROW(__sync_fetch_and_add),
754     BUILTIN_ROW(__sync_fetch_and_sub),
755     BUILTIN_ROW(__sync_fetch_and_or),
756     BUILTIN_ROW(__sync_fetch_and_and),
757     BUILTIN_ROW(__sync_fetch_and_xor),
758 
759     BUILTIN_ROW(__sync_add_and_fetch),
760     BUILTIN_ROW(__sync_sub_and_fetch),
761     BUILTIN_ROW(__sync_and_and_fetch),
762     BUILTIN_ROW(__sync_or_and_fetch),
763     BUILTIN_ROW(__sync_xor_and_fetch),
764 
765     BUILTIN_ROW(__sync_val_compare_and_swap),
766     BUILTIN_ROW(__sync_bool_compare_and_swap),
767     BUILTIN_ROW(__sync_lock_test_and_set),
768     BUILTIN_ROW(__sync_lock_release),
769     BUILTIN_ROW(__sync_swap)
770   };
771 #undef BUILTIN_ROW
772 
773   // Determine the index of the size.
774   unsigned SizeIndex;
775   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
776   case 1: SizeIndex = 0; break;
777   case 2: SizeIndex = 1; break;
778   case 4: SizeIndex = 2; break;
779   case 8: SizeIndex = 3; break;
780   case 16: SizeIndex = 4; break;
781   default:
782     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
783       << FirstArg->getType() << FirstArg->getSourceRange();
784     return ExprError();
785   }
786 
787   // Each of these builtins has one pointer argument, followed by some number of
788   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
789   // that we ignore.  Find out which row of BuiltinIndices to read from as well
790   // as the number of fixed args.
791   unsigned BuiltinID = FDecl->getBuiltinID();
792   unsigned BuiltinIndex, NumFixed = 1;
793   switch (BuiltinID) {
794   default: llvm_unreachable("Unknown overloaded atomic builtin!");
795   case Builtin::BI__sync_fetch_and_add:
796   case Builtin::BI__sync_fetch_and_add_1:
797   case Builtin::BI__sync_fetch_and_add_2:
798   case Builtin::BI__sync_fetch_and_add_4:
799   case Builtin::BI__sync_fetch_and_add_8:
800   case Builtin::BI__sync_fetch_and_add_16:
801     BuiltinIndex = 0;
802     break;
803 
804   case Builtin::BI__sync_fetch_and_sub:
805   case Builtin::BI__sync_fetch_and_sub_1:
806   case Builtin::BI__sync_fetch_and_sub_2:
807   case Builtin::BI__sync_fetch_and_sub_4:
808   case Builtin::BI__sync_fetch_and_sub_8:
809   case Builtin::BI__sync_fetch_and_sub_16:
810     BuiltinIndex = 1;
811     break;
812 
813   case Builtin::BI__sync_fetch_and_or:
814   case Builtin::BI__sync_fetch_and_or_1:
815   case Builtin::BI__sync_fetch_and_or_2:
816   case Builtin::BI__sync_fetch_and_or_4:
817   case Builtin::BI__sync_fetch_and_or_8:
818   case Builtin::BI__sync_fetch_and_or_16:
819     BuiltinIndex = 2;
820     break;
821 
822   case Builtin::BI__sync_fetch_and_and:
823   case Builtin::BI__sync_fetch_and_and_1:
824   case Builtin::BI__sync_fetch_and_and_2:
825   case Builtin::BI__sync_fetch_and_and_4:
826   case Builtin::BI__sync_fetch_and_and_8:
827   case Builtin::BI__sync_fetch_and_and_16:
828     BuiltinIndex = 3;
829     break;
830 
831   case Builtin::BI__sync_fetch_and_xor:
832   case Builtin::BI__sync_fetch_and_xor_1:
833   case Builtin::BI__sync_fetch_and_xor_2:
834   case Builtin::BI__sync_fetch_and_xor_4:
835   case Builtin::BI__sync_fetch_and_xor_8:
836   case Builtin::BI__sync_fetch_and_xor_16:
837     BuiltinIndex = 4;
838     break;
839 
840   case Builtin::BI__sync_add_and_fetch:
841   case Builtin::BI__sync_add_and_fetch_1:
842   case Builtin::BI__sync_add_and_fetch_2:
843   case Builtin::BI__sync_add_and_fetch_4:
844   case Builtin::BI__sync_add_and_fetch_8:
845   case Builtin::BI__sync_add_and_fetch_16:
846     BuiltinIndex = 5;
847     break;
848 
849   case Builtin::BI__sync_sub_and_fetch:
850   case Builtin::BI__sync_sub_and_fetch_1:
851   case Builtin::BI__sync_sub_and_fetch_2:
852   case Builtin::BI__sync_sub_and_fetch_4:
853   case Builtin::BI__sync_sub_and_fetch_8:
854   case Builtin::BI__sync_sub_and_fetch_16:
855     BuiltinIndex = 6;
856     break;
857 
858   case Builtin::BI__sync_and_and_fetch:
859   case Builtin::BI__sync_and_and_fetch_1:
860   case Builtin::BI__sync_and_and_fetch_2:
861   case Builtin::BI__sync_and_and_fetch_4:
862   case Builtin::BI__sync_and_and_fetch_8:
863   case Builtin::BI__sync_and_and_fetch_16:
864     BuiltinIndex = 7;
865     break;
866 
867   case Builtin::BI__sync_or_and_fetch:
868   case Builtin::BI__sync_or_and_fetch_1:
869   case Builtin::BI__sync_or_and_fetch_2:
870   case Builtin::BI__sync_or_and_fetch_4:
871   case Builtin::BI__sync_or_and_fetch_8:
872   case Builtin::BI__sync_or_and_fetch_16:
873     BuiltinIndex = 8;
874     break;
875 
876   case Builtin::BI__sync_xor_and_fetch:
877   case Builtin::BI__sync_xor_and_fetch_1:
878   case Builtin::BI__sync_xor_and_fetch_2:
879   case Builtin::BI__sync_xor_and_fetch_4:
880   case Builtin::BI__sync_xor_and_fetch_8:
881   case Builtin::BI__sync_xor_and_fetch_16:
882     BuiltinIndex = 9;
883     break;
884 
885   case Builtin::BI__sync_val_compare_and_swap:
886   case Builtin::BI__sync_val_compare_and_swap_1:
887   case Builtin::BI__sync_val_compare_and_swap_2:
888   case Builtin::BI__sync_val_compare_and_swap_4:
889   case Builtin::BI__sync_val_compare_and_swap_8:
890   case Builtin::BI__sync_val_compare_and_swap_16:
891     BuiltinIndex = 10;
892     NumFixed = 2;
893     break;
894 
895   case Builtin::BI__sync_bool_compare_and_swap:
896   case Builtin::BI__sync_bool_compare_and_swap_1:
897   case Builtin::BI__sync_bool_compare_and_swap_2:
898   case Builtin::BI__sync_bool_compare_and_swap_4:
899   case Builtin::BI__sync_bool_compare_and_swap_8:
900   case Builtin::BI__sync_bool_compare_and_swap_16:
901     BuiltinIndex = 11;
902     NumFixed = 2;
903     ResultType = Context.BoolTy;
904     break;
905 
906   case Builtin::BI__sync_lock_test_and_set:
907   case Builtin::BI__sync_lock_test_and_set_1:
908   case Builtin::BI__sync_lock_test_and_set_2:
909   case Builtin::BI__sync_lock_test_and_set_4:
910   case Builtin::BI__sync_lock_test_and_set_8:
911   case Builtin::BI__sync_lock_test_and_set_16:
912     BuiltinIndex = 12;
913     break;
914 
915   case Builtin::BI__sync_lock_release:
916   case Builtin::BI__sync_lock_release_1:
917   case Builtin::BI__sync_lock_release_2:
918   case Builtin::BI__sync_lock_release_4:
919   case Builtin::BI__sync_lock_release_8:
920   case Builtin::BI__sync_lock_release_16:
921     BuiltinIndex = 13;
922     NumFixed = 0;
923     ResultType = Context.VoidTy;
924     break;
925 
926   case Builtin::BI__sync_swap:
927   case Builtin::BI__sync_swap_1:
928   case Builtin::BI__sync_swap_2:
929   case Builtin::BI__sync_swap_4:
930   case Builtin::BI__sync_swap_8:
931   case Builtin::BI__sync_swap_16:
932     BuiltinIndex = 14;
933     break;
934   }
935 
936   // Now that we know how many fixed arguments we expect, first check that we
937   // have at least that many.
938   if (TheCall->getNumArgs() < 1+NumFixed) {
939     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
940       << 0 << 1+NumFixed << TheCall->getNumArgs()
941       << TheCall->getCallee()->getSourceRange();
942     return ExprError();
943   }
944 
945   // Get the decl for the concrete builtin from this, we can tell what the
946   // concrete integer type we should convert to is.
947   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
948   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
949   IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
950   FunctionDecl *NewBuiltinDecl =
951     cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
952                                            TUScope, false, DRE->getLocStart()));
953 
954   // The first argument --- the pointer --- has a fixed type; we
955   // deduce the types of the rest of the arguments accordingly.  Walk
956   // the remaining arguments, converting them to the deduced value type.
957   for (unsigned i = 0; i != NumFixed; ++i) {
958     ExprResult Arg = TheCall->getArg(i+1);
959 
960     // GCC does an implicit conversion to the pointer or integer ValType.  This
961     // can fail in some cases (1i -> int**), check for this error case now.
962     // Initialize the argument.
963     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
964                                                    ValType, /*consume*/ false);
965     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
966     if (Arg.isInvalid())
967       return ExprError();
968 
969     // Okay, we have something that *can* be converted to the right type.  Check
970     // to see if there is a potentially weird extension going on here.  This can
971     // happen when you do an atomic operation on something like an char* and
972     // pass in 42.  The 42 gets converted to char.  This is even more strange
973     // for things like 45.123 -> char, etc.
974     // FIXME: Do this check.
975     TheCall->setArg(i+1, Arg.take());
976   }
977 
978   ASTContext& Context = this->getASTContext();
979 
980   // Create a new DeclRefExpr to refer to the new decl.
981   DeclRefExpr* NewDRE = DeclRefExpr::Create(
982       Context,
983       DRE->getQualifierLoc(),
984       SourceLocation(),
985       NewBuiltinDecl,
986       DRE->getLocation(),
987       NewBuiltinDecl->getType(),
988       DRE->getValueKind());
989 
990   // Set the callee in the CallExpr.
991   // FIXME: This leaks the original parens and implicit casts.
992   ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
993   if (PromotedCall.isInvalid())
994     return ExprError();
995   TheCall->setCallee(PromotedCall.take());
996 
997   // Change the result type of the call to match the original value type. This
998   // is arbitrary, but the codegen for these builtins ins design to handle it
999   // gracefully.
1000   TheCall->setType(ResultType);
1001 
1002   return move(TheCallResult);
1003 }
1004 
1005 /// CheckObjCString - Checks that the argument to the builtin
1006 /// CFString constructor is correct
1007 /// Note: It might also make sense to do the UTF-16 conversion here (would
1008 /// simplify the backend).
1009 bool Sema::CheckObjCString(Expr *Arg) {
1010   Arg = Arg->IgnoreParenCasts();
1011   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1012 
1013   if (!Literal || !Literal->isAscii()) {
1014     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1015       << Arg->getSourceRange();
1016     return true;
1017   }
1018 
1019   if (Literal->containsNonAsciiOrNull()) {
1020     StringRef String = Literal->getString();
1021     unsigned NumBytes = String.size();
1022     SmallVector<UTF16, 128> ToBuf(NumBytes);
1023     const UTF8 *FromPtr = (UTF8 *)String.data();
1024     UTF16 *ToPtr = &ToBuf[0];
1025 
1026     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1027                                                  &ToPtr, ToPtr + NumBytes,
1028                                                  strictConversion);
1029     // Check for conversion failure.
1030     if (Result != conversionOK)
1031       Diag(Arg->getLocStart(),
1032            diag::warn_cfstring_truncated) << Arg->getSourceRange();
1033   }
1034   return false;
1035 }
1036 
1037 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1038 /// Emit an error and return true on failure, return false on success.
1039 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1040   Expr *Fn = TheCall->getCallee();
1041   if (TheCall->getNumArgs() > 2) {
1042     Diag(TheCall->getArg(2)->getLocStart(),
1043          diag::err_typecheck_call_too_many_args)
1044       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1045       << Fn->getSourceRange()
1046       << SourceRange(TheCall->getArg(2)->getLocStart(),
1047                      (*(TheCall->arg_end()-1))->getLocEnd());
1048     return true;
1049   }
1050 
1051   if (TheCall->getNumArgs() < 2) {
1052     return Diag(TheCall->getLocEnd(),
1053       diag::err_typecheck_call_too_few_args_at_least)
1054       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1055   }
1056 
1057   // Type-check the first argument normally.
1058   if (checkBuiltinArgument(*this, TheCall, 0))
1059     return true;
1060 
1061   // Determine whether the current function is variadic or not.
1062   BlockScopeInfo *CurBlock = getCurBlock();
1063   bool isVariadic;
1064   if (CurBlock)
1065     isVariadic = CurBlock->TheDecl->isVariadic();
1066   else if (FunctionDecl *FD = getCurFunctionDecl())
1067     isVariadic = FD->isVariadic();
1068   else
1069     isVariadic = getCurMethodDecl()->isVariadic();
1070 
1071   if (!isVariadic) {
1072     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1073     return true;
1074   }
1075 
1076   // Verify that the second argument to the builtin is the last argument of the
1077   // current function or method.
1078   bool SecondArgIsLastNamedArgument = false;
1079   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1080 
1081   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1082     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1083       // FIXME: This isn't correct for methods (results in bogus warning).
1084       // Get the last formal in the current function.
1085       const ParmVarDecl *LastArg;
1086       if (CurBlock)
1087         LastArg = *(CurBlock->TheDecl->param_end()-1);
1088       else if (FunctionDecl *FD = getCurFunctionDecl())
1089         LastArg = *(FD->param_end()-1);
1090       else
1091         LastArg = *(getCurMethodDecl()->param_end()-1);
1092       SecondArgIsLastNamedArgument = PV == LastArg;
1093     }
1094   }
1095 
1096   if (!SecondArgIsLastNamedArgument)
1097     Diag(TheCall->getArg(1)->getLocStart(),
1098          diag::warn_second_parameter_of_va_start_not_last_named_argument);
1099   return false;
1100 }
1101 
1102 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1103 /// friends.  This is declared to take (...), so we have to check everything.
1104 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1105   if (TheCall->getNumArgs() < 2)
1106     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1107       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1108   if (TheCall->getNumArgs() > 2)
1109     return Diag(TheCall->getArg(2)->getLocStart(),
1110                 diag::err_typecheck_call_too_many_args)
1111       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1112       << SourceRange(TheCall->getArg(2)->getLocStart(),
1113                      (*(TheCall->arg_end()-1))->getLocEnd());
1114 
1115   ExprResult OrigArg0 = TheCall->getArg(0);
1116   ExprResult OrigArg1 = TheCall->getArg(1);
1117 
1118   // Do standard promotions between the two arguments, returning their common
1119   // type.
1120   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1121   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1122     return true;
1123 
1124   // Make sure any conversions are pushed back into the call; this is
1125   // type safe since unordered compare builtins are declared as "_Bool
1126   // foo(...)".
1127   TheCall->setArg(0, OrigArg0.get());
1128   TheCall->setArg(1, OrigArg1.get());
1129 
1130   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1131     return false;
1132 
1133   // If the common type isn't a real floating type, then the arguments were
1134   // invalid for this operation.
1135   if (!Res->isRealFloatingType())
1136     return Diag(OrigArg0.get()->getLocStart(),
1137                 diag::err_typecheck_call_invalid_ordered_compare)
1138       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1139       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1140 
1141   return false;
1142 }
1143 
1144 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1145 /// __builtin_isnan and friends.  This is declared to take (...), so we have
1146 /// to check everything. We expect the last argument to be a floating point
1147 /// value.
1148 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1149   if (TheCall->getNumArgs() < NumArgs)
1150     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1151       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1152   if (TheCall->getNumArgs() > NumArgs)
1153     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1154                 diag::err_typecheck_call_too_many_args)
1155       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1156       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1157                      (*(TheCall->arg_end()-1))->getLocEnd());
1158 
1159   Expr *OrigArg = TheCall->getArg(NumArgs-1);
1160 
1161   if (OrigArg->isTypeDependent())
1162     return false;
1163 
1164   // This operation requires a non-_Complex floating-point number.
1165   if (!OrigArg->getType()->isRealFloatingType())
1166     return Diag(OrigArg->getLocStart(),
1167                 diag::err_typecheck_call_invalid_unary_fp)
1168       << OrigArg->getType() << OrigArg->getSourceRange();
1169 
1170   // If this is an implicit conversion from float -> double, remove it.
1171   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1172     Expr *CastArg = Cast->getSubExpr();
1173     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1174       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1175              "promotion from float to double is the only expected cast here");
1176       Cast->setSubExpr(0);
1177       TheCall->setArg(NumArgs-1, CastArg);
1178       OrigArg = CastArg;
1179     }
1180   }
1181 
1182   return false;
1183 }
1184 
1185 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1186 // This is declared to take (...), so we have to check everything.
1187 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1188   if (TheCall->getNumArgs() < 2)
1189     return ExprError(Diag(TheCall->getLocEnd(),
1190                           diag::err_typecheck_call_too_few_args_at_least)
1191       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1192       << TheCall->getSourceRange());
1193 
1194   // Determine which of the following types of shufflevector we're checking:
1195   // 1) unary, vector mask: (lhs, mask)
1196   // 2) binary, vector mask: (lhs, rhs, mask)
1197   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1198   QualType resType = TheCall->getArg(0)->getType();
1199   unsigned numElements = 0;
1200 
1201   if (!TheCall->getArg(0)->isTypeDependent() &&
1202       !TheCall->getArg(1)->isTypeDependent()) {
1203     QualType LHSType = TheCall->getArg(0)->getType();
1204     QualType RHSType = TheCall->getArg(1)->getType();
1205 
1206     if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
1207       Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
1208         << SourceRange(TheCall->getArg(0)->getLocStart(),
1209                        TheCall->getArg(1)->getLocEnd());
1210       return ExprError();
1211     }
1212 
1213     numElements = LHSType->getAs<VectorType>()->getNumElements();
1214     unsigned numResElements = TheCall->getNumArgs() - 2;
1215 
1216     // Check to see if we have a call with 2 vector arguments, the unary shuffle
1217     // with mask.  If so, verify that RHS is an integer vector type with the
1218     // same number of elts as lhs.
1219     if (TheCall->getNumArgs() == 2) {
1220       if (!RHSType->hasIntegerRepresentation() ||
1221           RHSType->getAs<VectorType>()->getNumElements() != numElements)
1222         Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1223           << SourceRange(TheCall->getArg(1)->getLocStart(),
1224                          TheCall->getArg(1)->getLocEnd());
1225       numResElements = numElements;
1226     }
1227     else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1228       Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1229         << SourceRange(TheCall->getArg(0)->getLocStart(),
1230                        TheCall->getArg(1)->getLocEnd());
1231       return ExprError();
1232     } else if (numElements != numResElements) {
1233       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1234       resType = Context.getVectorType(eltType, numResElements,
1235                                       VectorType::GenericVector);
1236     }
1237   }
1238 
1239   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1240     if (TheCall->getArg(i)->isTypeDependent() ||
1241         TheCall->getArg(i)->isValueDependent())
1242       continue;
1243 
1244     llvm::APSInt Result(32);
1245     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1246       return ExprError(Diag(TheCall->getLocStart(),
1247                   diag::err_shufflevector_nonconstant_argument)
1248                 << TheCall->getArg(i)->getSourceRange());
1249 
1250     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1251       return ExprError(Diag(TheCall->getLocStart(),
1252                   diag::err_shufflevector_argument_too_large)
1253                << TheCall->getArg(i)->getSourceRange());
1254   }
1255 
1256   SmallVector<Expr*, 32> exprs;
1257 
1258   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1259     exprs.push_back(TheCall->getArg(i));
1260     TheCall->setArg(i, 0);
1261   }
1262 
1263   return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
1264                                             exprs.size(), resType,
1265                                             TheCall->getCallee()->getLocStart(),
1266                                             TheCall->getRParenLoc()));
1267 }
1268 
1269 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1270 // This is declared to take (const void*, ...) and can take two
1271 // optional constant int args.
1272 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1273   unsigned NumArgs = TheCall->getNumArgs();
1274 
1275   if (NumArgs > 3)
1276     return Diag(TheCall->getLocEnd(),
1277              diag::err_typecheck_call_too_many_args_at_most)
1278              << 0 /*function call*/ << 3 << NumArgs
1279              << TheCall->getSourceRange();
1280 
1281   // Argument 0 is checked for us and the remaining arguments must be
1282   // constant integers.
1283   for (unsigned i = 1; i != NumArgs; ++i) {
1284     Expr *Arg = TheCall->getArg(i);
1285 
1286     llvm::APSInt Result;
1287     if (SemaBuiltinConstantArg(TheCall, i, Result))
1288       return true;
1289 
1290     // FIXME: gcc issues a warning and rewrites these to 0. These
1291     // seems especially odd for the third argument since the default
1292     // is 3.
1293     if (i == 1) {
1294       if (Result.getLimitedValue() > 1)
1295         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1296              << "0" << "1" << Arg->getSourceRange();
1297     } else {
1298       if (Result.getLimitedValue() > 3)
1299         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1300             << "0" << "3" << Arg->getSourceRange();
1301     }
1302   }
1303 
1304   return false;
1305 }
1306 
1307 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1308 /// TheCall is a constant expression.
1309 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1310                                   llvm::APSInt &Result) {
1311   Expr *Arg = TheCall->getArg(ArgNum);
1312   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1313   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1314 
1315   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1316 
1317   if (!Arg->isIntegerConstantExpr(Result, Context))
1318     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1319                 << FDecl->getDeclName() <<  Arg->getSourceRange();
1320 
1321   return false;
1322 }
1323 
1324 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1325 /// int type). This simply type checks that type is one of the defined
1326 /// constants (0-3).
1327 // For compatibility check 0-3, llvm only handles 0 and 2.
1328 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1329   llvm::APSInt Result;
1330 
1331   // Check constant-ness first.
1332   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1333     return true;
1334 
1335   Expr *Arg = TheCall->getArg(1);
1336   if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1337     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1338              << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1339   }
1340 
1341   return false;
1342 }
1343 
1344 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1345 /// This checks that val is a constant 1.
1346 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1347   Expr *Arg = TheCall->getArg(1);
1348   llvm::APSInt Result;
1349 
1350   // TODO: This is less than ideal. Overload this to take a value.
1351   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1352     return true;
1353 
1354   if (Result != 1)
1355     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1356              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1357 
1358   return false;
1359 }
1360 
1361 // Handle i > 1 ? "x" : "y", recursively.
1362 bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1363                                   unsigned NumArgs, bool HasVAListArg,
1364                                   unsigned format_idx, unsigned firstDataArg,
1365                                   FormatStringType Type, bool inFunctionCall) {
1366  tryAgain:
1367   if (E->isTypeDependent() || E->isValueDependent())
1368     return false;
1369 
1370   E = E->IgnoreParenCasts();
1371 
1372   if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1373     // Technically -Wformat-nonliteral does not warn about this case.
1374     // The behavior of printf and friends in this case is implementation
1375     // dependent.  Ideally if the format string cannot be null then
1376     // it should have a 'nonnull' attribute in the function prototype.
1377     return true;
1378 
1379   switch (E->getStmtClass()) {
1380   case Stmt::BinaryConditionalOperatorClass:
1381   case Stmt::ConditionalOperatorClass: {
1382     const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
1383     return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
1384                                   format_idx, firstDataArg, Type,
1385                                   inFunctionCall)
1386        && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
1387                                  format_idx, firstDataArg, Type,
1388                                  inFunctionCall);
1389   }
1390 
1391   case Stmt::ImplicitCastExprClass: {
1392     E = cast<ImplicitCastExpr>(E)->getSubExpr();
1393     goto tryAgain;
1394   }
1395 
1396   case Stmt::OpaqueValueExprClass:
1397     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1398       E = src;
1399       goto tryAgain;
1400     }
1401     return false;
1402 
1403   case Stmt::PredefinedExprClass:
1404     // While __func__, etc., are technically not string literals, they
1405     // cannot contain format specifiers and thus are not a security
1406     // liability.
1407     return true;
1408 
1409   case Stmt::DeclRefExprClass: {
1410     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
1411 
1412     // As an exception, do not flag errors for variables binding to
1413     // const string literals.
1414     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1415       bool isConstant = false;
1416       QualType T = DR->getType();
1417 
1418       if (const ArrayType *AT = Context.getAsArrayType(T)) {
1419         isConstant = AT->getElementType().isConstant(Context);
1420       } else if (const PointerType *PT = T->getAs<PointerType>()) {
1421         isConstant = T.isConstant(Context) &&
1422                      PT->getPointeeType().isConstant(Context);
1423       } else if (T->isObjCObjectPointerType()) {
1424         // In ObjC, there is usually no "const ObjectPointer" type,
1425         // so don't check if the pointee type is constant.
1426         isConstant = T.isConstant(Context);
1427       }
1428 
1429       if (isConstant) {
1430         if (const Expr *Init = VD->getAnyInitializer())
1431           return SemaCheckStringLiteral(Init, Args, NumArgs,
1432                                         HasVAListArg, format_idx, firstDataArg,
1433                                         Type, /*inFunctionCall*/false);
1434       }
1435 
1436       // For vprintf* functions (i.e., HasVAListArg==true), we add a
1437       // special check to see if the format string is a function parameter
1438       // of the function calling the printf function.  If the function
1439       // has an attribute indicating it is a printf-like function, then we
1440       // should suppress warnings concerning non-literals being used in a call
1441       // to a vprintf function.  For example:
1442       //
1443       // void
1444       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1445       //      va_list ap;
1446       //      va_start(ap, fmt);
1447       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
1448       //      ...
1449       //
1450       //
1451       //  FIXME: We don't have full attribute support yet, so just check to see
1452       //    if the argument is a DeclRefExpr that references a parameter.  We'll
1453       //    add proper support for checking the attribute later.
1454       if (HasVAListArg)
1455         if (isa<ParmVarDecl>(VD))
1456           return true;
1457     }
1458 
1459     return false;
1460   }
1461 
1462   case Stmt::CallExprClass:
1463   case Stmt::CXXMemberCallExprClass: {
1464     const CallExpr *CE = cast<CallExpr>(E);
1465     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1466       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1467         unsigned ArgIndex = FA->getFormatIdx();
1468         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1469           if (MD->isInstance())
1470             --ArgIndex;
1471         const Expr *Arg = CE->getArg(ArgIndex - 1);
1472 
1473         return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
1474                                       format_idx, firstDataArg, Type,
1475                                       inFunctionCall);
1476       }
1477     }
1478 
1479     return false;
1480   }
1481   case Stmt::ObjCStringLiteralClass:
1482   case Stmt::StringLiteralClass: {
1483     const StringLiteral *StrE = NULL;
1484 
1485     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
1486       StrE = ObjCFExpr->getString();
1487     else
1488       StrE = cast<StringLiteral>(E);
1489 
1490     if (StrE) {
1491       CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
1492                         firstDataArg, Type, inFunctionCall);
1493       return true;
1494     }
1495 
1496     return false;
1497   }
1498 
1499   default:
1500     return false;
1501   }
1502 }
1503 
1504 void
1505 Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1506                             const Expr * const *ExprArgs,
1507                             SourceLocation CallSiteLoc) {
1508   for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1509                                   e = NonNull->args_end();
1510        i != e; ++i) {
1511     const Expr *ArgExpr = ExprArgs[*i];
1512     if (ArgExpr->isNullPointerConstant(Context,
1513                                        Expr::NPC_ValueDependentIsNotNull))
1514       Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1515   }
1516 }
1517 
1518 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1519   return llvm::StringSwitch<FormatStringType>(Format->getType())
1520   .Case("scanf", FST_Scanf)
1521   .Cases("printf", "printf0", FST_Printf)
1522   .Cases("NSString", "CFString", FST_NSString)
1523   .Case("strftime", FST_Strftime)
1524   .Case("strfmon", FST_Strfmon)
1525   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1526   .Default(FST_Unknown);
1527 }
1528 
1529 /// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1530 /// functions) for correct use of format strings.
1531 void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1532   bool IsCXXMember = false;
1533   // The way the format attribute works in GCC, the implicit this argument
1534   // of member functions is counted. However, it doesn't appear in our own
1535   // lists, so decrement format_idx in that case.
1536   IsCXXMember = isa<CXXMemberCallExpr>(TheCall);
1537   CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1538                        IsCXXMember, TheCall->getRParenLoc(),
1539                        TheCall->getCallee()->getSourceRange());
1540 }
1541 
1542 void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1543                                 unsigned NumArgs, bool IsCXXMember,
1544                                 SourceLocation Loc, SourceRange Range) {
1545   bool HasVAListArg = Format->getFirstArg() == 0;
1546   unsigned format_idx = Format->getFormatIdx() - 1;
1547   unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1548   if (IsCXXMember) {
1549     if (format_idx == 0)
1550       return;
1551     --format_idx;
1552     if(firstDataArg != 0)
1553       --firstDataArg;
1554   }
1555   CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx,
1556                        firstDataArg, GetFormatStringType(Format), Loc, Range);
1557 }
1558 
1559 void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
1560                                 bool HasVAListArg, unsigned format_idx,
1561                                 unsigned firstDataArg, FormatStringType Type,
1562                                 SourceLocation Loc, SourceRange Range) {
1563   // CHECK: printf/scanf-like function is called with no format string.
1564   if (format_idx >= NumArgs) {
1565     Diag(Loc, diag::warn_missing_format_string) << Range;
1566     return;
1567   }
1568 
1569   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
1570 
1571   // CHECK: format string is not a string literal.
1572   //
1573   // Dynamically generated format strings are difficult to
1574   // automatically vet at compile time.  Requiring that format strings
1575   // are string literals: (1) permits the checking of format strings by
1576   // the compiler and thereby (2) can practically remove the source of
1577   // many format string exploits.
1578 
1579   // Format string can be either ObjC string (e.g. @"%d") or
1580   // C string (e.g. "%d")
1581   // ObjC string uses the same format specifiers as C string, so we can use
1582   // the same format string checking logic for both ObjC and C strings.
1583   if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
1584                              format_idx, firstDataArg, Type))
1585     return;  // Literal format string found, check done!
1586 
1587   // Strftime is particular as it always uses a single 'time' argument,
1588   // so it is safe to pass a non-literal string.
1589   if (Type == FST_Strftime)
1590     return;
1591 
1592   // Do not emit diag when the string param is a macro expansion and the
1593   // format is either NSString or CFString. This is a hack to prevent
1594   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1595   // which are usually used in place of NS and CF string literals.
1596   if (Type == FST_NSString && Args[format_idx]->getLocStart().isMacroID())
1597     return;
1598 
1599   // If there are no arguments specified, warn with -Wformat-security, otherwise
1600   // warn only with -Wformat-nonliteral.
1601   if (NumArgs == format_idx+1)
1602     Diag(Args[format_idx]->getLocStart(),
1603          diag::warn_format_nonliteral_noargs)
1604       << OrigFormatExpr->getSourceRange();
1605   else
1606     Diag(Args[format_idx]->getLocStart(),
1607          diag::warn_format_nonliteral)
1608            << OrigFormatExpr->getSourceRange();
1609 }
1610 
1611 namespace {
1612 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1613 protected:
1614   Sema &S;
1615   const StringLiteral *FExpr;
1616   const Expr *OrigFormatExpr;
1617   const unsigned FirstDataArg;
1618   const unsigned NumDataArgs;
1619   const bool IsObjCLiteral;
1620   const char *Beg; // Start of format string.
1621   const bool HasVAListArg;
1622   const Expr * const *Args;
1623   const unsigned NumArgs;
1624   unsigned FormatIdx;
1625   llvm::BitVector CoveredArgs;
1626   bool usesPositionalArgs;
1627   bool atFirstArg;
1628   bool inFunctionCall;
1629 public:
1630   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
1631                      const Expr *origFormatExpr, unsigned firstDataArg,
1632                      unsigned numDataArgs, bool isObjCLiteral,
1633                      const char *beg, bool hasVAListArg,
1634                      Expr **args, unsigned numArgs,
1635                      unsigned formatIdx, bool inFunctionCall)
1636     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1637       FirstDataArg(firstDataArg),
1638       NumDataArgs(numDataArgs),
1639       IsObjCLiteral(isObjCLiteral), Beg(beg),
1640       HasVAListArg(hasVAListArg),
1641       Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
1642       usesPositionalArgs(false), atFirstArg(true),
1643       inFunctionCall(inFunctionCall) {
1644         CoveredArgs.resize(numDataArgs);
1645         CoveredArgs.reset();
1646       }
1647 
1648   void DoneProcessing();
1649 
1650   void HandleIncompleteSpecifier(const char *startSpecifier,
1651                                  unsigned specifierLen);
1652 
1653   virtual void HandleInvalidPosition(const char *startSpecifier,
1654                                      unsigned specifierLen,
1655                                      analyze_format_string::PositionContext p);
1656 
1657   virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1658 
1659   void HandleNullChar(const char *nullCharacter);
1660 
1661   template <typename Range>
1662   static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1663                                    const Expr *ArgumentExpr,
1664                                    PartialDiagnostic PDiag,
1665                                    SourceLocation StringLoc,
1666                                    bool IsStringLocation, Range StringRange,
1667                                    FixItHint Fixit = FixItHint());
1668 
1669 protected:
1670   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1671                                         const char *startSpec,
1672                                         unsigned specifierLen,
1673                                         const char *csStart, unsigned csLen);
1674 
1675   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1676                                          const char *startSpec,
1677                                          unsigned specifierLen);
1678 
1679   SourceRange getFormatStringRange();
1680   CharSourceRange getSpecifierRange(const char *startSpecifier,
1681                                     unsigned specifierLen);
1682   SourceLocation getLocationOfByte(const char *x);
1683 
1684   const Expr *getDataArg(unsigned i) const;
1685 
1686   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1687                     const analyze_format_string::ConversionSpecifier &CS,
1688                     const char *startSpecifier, unsigned specifierLen,
1689                     unsigned argIndex);
1690 
1691   template <typename Range>
1692   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1693                             bool IsStringLocation, Range StringRange,
1694                             FixItHint Fixit = FixItHint());
1695 
1696   void CheckPositionalAndNonpositionalArgs(
1697       const analyze_format_string::FormatSpecifier *FS);
1698 };
1699 }
1700 
1701 SourceRange CheckFormatHandler::getFormatStringRange() {
1702   return OrigFormatExpr->getSourceRange();
1703 }
1704 
1705 CharSourceRange CheckFormatHandler::
1706 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1707   SourceLocation Start = getLocationOfByte(startSpecifier);
1708   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
1709 
1710   // Advance the end SourceLocation by one due to half-open ranges.
1711   End = End.getLocWithOffset(1);
1712 
1713   return CharSourceRange::getCharRange(Start, End);
1714 }
1715 
1716 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
1717   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1718 }
1719 
1720 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1721                                                    unsigned specifierLen){
1722   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1723                        getLocationOfByte(startSpecifier),
1724                        /*IsStringLocation*/true,
1725                        getSpecifierRange(startSpecifier, specifierLen));
1726 }
1727 
1728 void
1729 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1730                                      analyze_format_string::PositionContext p) {
1731   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1732                          << (unsigned) p,
1733                        getLocationOfByte(startPos), /*IsStringLocation*/true,
1734                        getSpecifierRange(startPos, posLen));
1735 }
1736 
1737 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
1738                                             unsigned posLen) {
1739   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1740                                getLocationOfByte(startPos),
1741                                /*IsStringLocation*/true,
1742                                getSpecifierRange(startPos, posLen));
1743 }
1744 
1745 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1746   if (!IsObjCLiteral) {
1747     // The presence of a null character is likely an error.
1748     EmitFormatDiagnostic(
1749       S.PDiag(diag::warn_printf_format_string_contains_null_char),
1750       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1751       getFormatStringRange());
1752   }
1753 }
1754 
1755 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1756   return Args[FirstDataArg + i];
1757 }
1758 
1759 void CheckFormatHandler::DoneProcessing() {
1760     // Does the number of data arguments exceed the number of
1761     // format conversions in the format string?
1762   if (!HasVAListArg) {
1763       // Find any arguments that weren't covered.
1764     CoveredArgs.flip();
1765     signed notCoveredArg = CoveredArgs.find_first();
1766     if (notCoveredArg >= 0) {
1767       assert((unsigned)notCoveredArg < NumDataArgs);
1768       EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1769                            getDataArg((unsigned) notCoveredArg)->getLocStart(),
1770                            /*IsStringLocation*/false, getFormatStringRange());
1771     }
1772   }
1773 }
1774 
1775 bool
1776 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1777                                                      SourceLocation Loc,
1778                                                      const char *startSpec,
1779                                                      unsigned specifierLen,
1780                                                      const char *csStart,
1781                                                      unsigned csLen) {
1782 
1783   bool keepGoing = true;
1784   if (argIndex < NumDataArgs) {
1785     // Consider the argument coverered, even though the specifier doesn't
1786     // make sense.
1787     CoveredArgs.set(argIndex);
1788   }
1789   else {
1790     // If argIndex exceeds the number of data arguments we
1791     // don't issue a warning because that is just a cascade of warnings (and
1792     // they may have intended '%%' anyway). We don't want to continue processing
1793     // the format string after this point, however, as we will like just get
1794     // gibberish when trying to match arguments.
1795     keepGoing = false;
1796   }
1797 
1798   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1799                          << StringRef(csStart, csLen),
1800                        Loc, /*IsStringLocation*/true,
1801                        getSpecifierRange(startSpec, specifierLen));
1802 
1803   return keepGoing;
1804 }
1805 
1806 void
1807 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1808                                                       const char *startSpec,
1809                                                       unsigned specifierLen) {
1810   EmitFormatDiagnostic(
1811     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1812     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1813 }
1814 
1815 bool
1816 CheckFormatHandler::CheckNumArgs(
1817   const analyze_format_string::FormatSpecifier &FS,
1818   const analyze_format_string::ConversionSpecifier &CS,
1819   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1820 
1821   if (argIndex >= NumDataArgs) {
1822     PartialDiagnostic PDiag = FS.usesPositionalArg()
1823       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1824            << (argIndex+1) << NumDataArgs)
1825       : S.PDiag(diag::warn_printf_insufficient_data_args);
1826     EmitFormatDiagnostic(
1827       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1828       getSpecifierRange(startSpecifier, specifierLen));
1829     return false;
1830   }
1831   return true;
1832 }
1833 
1834 template<typename Range>
1835 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1836                                               SourceLocation Loc,
1837                                               bool IsStringLocation,
1838                                               Range StringRange,
1839                                               FixItHint FixIt) {
1840   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
1841                        Loc, IsStringLocation, StringRange, FixIt);
1842 }
1843 
1844 /// \brief If the format string is not within the funcion call, emit a note
1845 /// so that the function call and string are in diagnostic messages.
1846 ///
1847 /// \param inFunctionCall if true, the format string is within the function
1848 /// call and only one diagnostic message will be produced.  Otherwise, an
1849 /// extra note will be emitted pointing to location of the format string.
1850 ///
1851 /// \param ArgumentExpr the expression that is passed as the format string
1852 /// argument in the function call.  Used for getting locations when two
1853 /// diagnostics are emitted.
1854 ///
1855 /// \param PDiag the callee should already have provided any strings for the
1856 /// diagnostic message.  This function only adds locations and fixits
1857 /// to diagnostics.
1858 ///
1859 /// \param Loc primary location for diagnostic.  If two diagnostics are
1860 /// required, one will be at Loc and a new SourceLocation will be created for
1861 /// the other one.
1862 ///
1863 /// \param IsStringLocation if true, Loc points to the format string should be
1864 /// used for the note.  Otherwise, Loc points to the argument list and will
1865 /// be used with PDiag.
1866 ///
1867 /// \param StringRange some or all of the string to highlight.  This is
1868 /// templated so it can accept either a CharSourceRange or a SourceRange.
1869 ///
1870 /// \param Fixit optional fix it hint for the format string.
1871 template<typename Range>
1872 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1873                                               const Expr *ArgumentExpr,
1874                                               PartialDiagnostic PDiag,
1875                                               SourceLocation Loc,
1876                                               bool IsStringLocation,
1877                                               Range StringRange,
1878                                               FixItHint FixIt) {
1879   if (InFunctionCall)
1880     S.Diag(Loc, PDiag) << StringRange << FixIt;
1881   else {
1882     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1883       << ArgumentExpr->getSourceRange();
1884     S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1885            diag::note_format_string_defined)
1886       << StringRange << FixIt;
1887   }
1888 }
1889 
1890 //===--- CHECK: Printf format string checking ------------------------------===//
1891 
1892 namespace {
1893 class CheckPrintfHandler : public CheckFormatHandler {
1894 public:
1895   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1896                      const Expr *origFormatExpr, unsigned firstDataArg,
1897                      unsigned numDataArgs, bool isObjCLiteral,
1898                      const char *beg, bool hasVAListArg,
1899                      Expr **Args, unsigned NumArgs,
1900                      unsigned formatIdx, bool inFunctionCall)
1901   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1902                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
1903                        Args, NumArgs, formatIdx, inFunctionCall) {}
1904 
1905 
1906   bool HandleInvalidPrintfConversionSpecifier(
1907                                       const analyze_printf::PrintfSpecifier &FS,
1908                                       const char *startSpecifier,
1909                                       unsigned specifierLen);
1910 
1911   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1912                              const char *startSpecifier,
1913                              unsigned specifierLen);
1914 
1915   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1916                     const char *startSpecifier, unsigned specifierLen);
1917   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1918                            const analyze_printf::OptionalAmount &Amt,
1919                            unsigned type,
1920                            const char *startSpecifier, unsigned specifierLen);
1921   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1922                   const analyze_printf::OptionalFlag &flag,
1923                   const char *startSpecifier, unsigned specifierLen);
1924   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1925                          const analyze_printf::OptionalFlag &ignoredFlag,
1926                          const analyze_printf::OptionalFlag &flag,
1927                          const char *startSpecifier, unsigned specifierLen);
1928 };
1929 }
1930 
1931 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1932                                       const analyze_printf::PrintfSpecifier &FS,
1933                                       const char *startSpecifier,
1934                                       unsigned specifierLen) {
1935   const analyze_printf::PrintfConversionSpecifier &CS =
1936     FS.getConversionSpecifier();
1937 
1938   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1939                                           getLocationOfByte(CS.getStart()),
1940                                           startSpecifier, specifierLen,
1941                                           CS.getStart(), CS.getLength());
1942 }
1943 
1944 bool CheckPrintfHandler::HandleAmount(
1945                                const analyze_format_string::OptionalAmount &Amt,
1946                                unsigned k, const char *startSpecifier,
1947                                unsigned specifierLen) {
1948 
1949   if (Amt.hasDataArgument()) {
1950     if (!HasVAListArg) {
1951       unsigned argIndex = Amt.getArgIndex();
1952       if (argIndex >= NumDataArgs) {
1953         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1954                                << k,
1955                              getLocationOfByte(Amt.getStart()),
1956                              /*IsStringLocation*/true,
1957                              getSpecifierRange(startSpecifier, specifierLen));
1958         // Don't do any more checking.  We will just emit
1959         // spurious errors.
1960         return false;
1961       }
1962 
1963       // Type check the data argument.  It should be an 'int'.
1964       // Although not in conformance with C99, we also allow the argument to be
1965       // an 'unsigned int' as that is a reasonably safe case.  GCC also
1966       // doesn't emit a warning for that case.
1967       CoveredArgs.set(argIndex);
1968       const Expr *Arg = getDataArg(argIndex);
1969       QualType T = Arg->getType();
1970 
1971       const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1972       assert(ATR.isValid());
1973 
1974       if (!ATR.matchesType(S.Context, T)) {
1975         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
1976                                << k << ATR.getRepresentativeTypeName(S.Context)
1977                                << T << Arg->getSourceRange(),
1978                              getLocationOfByte(Amt.getStart()),
1979                              /*IsStringLocation*/true,
1980                              getSpecifierRange(startSpecifier, specifierLen));
1981         // Don't do any more checking.  We will just emit
1982         // spurious errors.
1983         return false;
1984       }
1985     }
1986   }
1987   return true;
1988 }
1989 
1990 void CheckPrintfHandler::HandleInvalidAmount(
1991                                       const analyze_printf::PrintfSpecifier &FS,
1992                                       const analyze_printf::OptionalAmount &Amt,
1993                                       unsigned type,
1994                                       const char *startSpecifier,
1995                                       unsigned specifierLen) {
1996   const analyze_printf::PrintfConversionSpecifier &CS =
1997     FS.getConversionSpecifier();
1998 
1999   FixItHint fixit =
2000     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2001       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2002                                  Amt.getConstantLength()))
2003       : FixItHint();
2004 
2005   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2006                          << type << CS.toString(),
2007                        getLocationOfByte(Amt.getStart()),
2008                        /*IsStringLocation*/true,
2009                        getSpecifierRange(startSpecifier, specifierLen),
2010                        fixit);
2011 }
2012 
2013 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2014                                     const analyze_printf::OptionalFlag &flag,
2015                                     const char *startSpecifier,
2016                                     unsigned specifierLen) {
2017   // Warn about pointless flag with a fixit removal.
2018   const analyze_printf::PrintfConversionSpecifier &CS =
2019     FS.getConversionSpecifier();
2020   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2021                          << flag.toString() << CS.toString(),
2022                        getLocationOfByte(flag.getPosition()),
2023                        /*IsStringLocation*/true,
2024                        getSpecifierRange(startSpecifier, specifierLen),
2025                        FixItHint::CreateRemoval(
2026                          getSpecifierRange(flag.getPosition(), 1)));
2027 }
2028 
2029 void CheckPrintfHandler::HandleIgnoredFlag(
2030                                 const analyze_printf::PrintfSpecifier &FS,
2031                                 const analyze_printf::OptionalFlag &ignoredFlag,
2032                                 const analyze_printf::OptionalFlag &flag,
2033                                 const char *startSpecifier,
2034                                 unsigned specifierLen) {
2035   // Warn about ignored flag with a fixit removal.
2036   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2037                          << ignoredFlag.toString() << flag.toString(),
2038                        getLocationOfByte(ignoredFlag.getPosition()),
2039                        /*IsStringLocation*/true,
2040                        getSpecifierRange(startSpecifier, specifierLen),
2041                        FixItHint::CreateRemoval(
2042                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
2043 }
2044 
2045 bool
2046 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
2047                                             &FS,
2048                                           const char *startSpecifier,
2049                                           unsigned specifierLen) {
2050 
2051   using namespace analyze_format_string;
2052   using namespace analyze_printf;
2053   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
2054 
2055   if (FS.consumesDataArgument()) {
2056     if (atFirstArg) {
2057         atFirstArg = false;
2058         usesPositionalArgs = FS.usesPositionalArg();
2059     }
2060     else if (usesPositionalArgs != FS.usesPositionalArg()) {
2061       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2062                                         startSpecifier, specifierLen);
2063       return false;
2064     }
2065   }
2066 
2067   // First check if the field width, precision, and conversion specifier
2068   // have matching data arguments.
2069   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2070                     startSpecifier, specifierLen)) {
2071     return false;
2072   }
2073 
2074   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2075                     startSpecifier, specifierLen)) {
2076     return false;
2077   }
2078 
2079   if (!CS.consumesDataArgument()) {
2080     // FIXME: Technically specifying a precision or field width here
2081     // makes no sense.  Worth issuing a warning at some point.
2082     return true;
2083   }
2084 
2085   // Consume the argument.
2086   unsigned argIndex = FS.getArgIndex();
2087   if (argIndex < NumDataArgs) {
2088     // The check to see if the argIndex is valid will come later.
2089     // We set the bit here because we may exit early from this
2090     // function if we encounter some other error.
2091     CoveredArgs.set(argIndex);
2092   }
2093 
2094   // Check for using an Objective-C specific conversion specifier
2095   // in a non-ObjC literal.
2096   if (!IsObjCLiteral && CS.isObjCArg()) {
2097     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2098                                                   specifierLen);
2099   }
2100 
2101   // Check for invalid use of field width
2102   if (!FS.hasValidFieldWidth()) {
2103     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
2104         startSpecifier, specifierLen);
2105   }
2106 
2107   // Check for invalid use of precision
2108   if (!FS.hasValidPrecision()) {
2109     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2110         startSpecifier, specifierLen);
2111   }
2112 
2113   // Check each flag does not conflict with any other component.
2114   if (!FS.hasValidThousandsGroupingPrefix())
2115     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
2116   if (!FS.hasValidLeadingZeros())
2117     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2118   if (!FS.hasValidPlusPrefix())
2119     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
2120   if (!FS.hasValidSpacePrefix())
2121     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
2122   if (!FS.hasValidAlternativeForm())
2123     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2124   if (!FS.hasValidLeftJustified())
2125     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2126 
2127   // Check that flags are not ignored by another flag
2128   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2129     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2130         startSpecifier, specifierLen);
2131   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2132     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2133             startSpecifier, specifierLen);
2134 
2135   // Check the length modifier is valid with the given conversion specifier.
2136   const LengthModifier &LM = FS.getLengthModifier();
2137   if (!FS.hasValidLengthModifier())
2138     EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2139                            << LM.toString() << CS.toString(),
2140                          getLocationOfByte(LM.getStart()),
2141                          /*IsStringLocation*/true,
2142                          getSpecifierRange(startSpecifier, specifierLen),
2143                          FixItHint::CreateRemoval(
2144                            getSpecifierRange(LM.getStart(),
2145                                              LM.getLength())));
2146 
2147   // Are we using '%n'?
2148   if (CS.getKind() == ConversionSpecifier::nArg) {
2149     // Issue a warning about this being a possible security issue.
2150     EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2151                          getLocationOfByte(CS.getStart()),
2152                          /*IsStringLocation*/true,
2153                          getSpecifierRange(startSpecifier, specifierLen));
2154     // Continue checking the other format specifiers.
2155     return true;
2156   }
2157 
2158   // The remaining checks depend on the data arguments.
2159   if (HasVAListArg)
2160     return true;
2161 
2162   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2163     return false;
2164 
2165   // Now type check the data expression that matches the
2166   // format specifier.
2167   const Expr *Ex = getDataArg(argIndex);
2168   const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
2169                                                            IsObjCLiteral);
2170   if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2171     // Check if we didn't match because of an implicit cast from a 'char'
2172     // or 'short' to an 'int'.  This is done because printf is a varargs
2173     // function.
2174     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
2175       if (ICE->getType() == S.Context.IntTy) {
2176         // All further checking is done on the subexpression.
2177         Ex = ICE->getSubExpr();
2178         if (ATR.matchesType(S.Context, Ex->getType()))
2179           return true;
2180       }
2181 
2182     // We may be able to offer a FixItHint if it is a supported type.
2183     PrintfSpecifier fixedFS = FS;
2184     bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions(),
2185                                    S.Context, IsObjCLiteral);
2186 
2187     if (success) {
2188       // Get the fix string from the fixed format specifier
2189       SmallString<128> buf;
2190       llvm::raw_svector_ostream os(buf);
2191       fixedFS.toString(os);
2192 
2193       EmitFormatDiagnostic(
2194         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2195           << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2196           << Ex->getSourceRange(),
2197         getLocationOfByte(CS.getStart()),
2198         /*IsStringLocation*/true,
2199         getSpecifierRange(startSpecifier, specifierLen),
2200         FixItHint::CreateReplacement(
2201           getSpecifierRange(startSpecifier, specifierLen),
2202           os.str()));
2203     }
2204     else {
2205       EmitFormatDiagnostic(
2206         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2207           << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2208           << getSpecifierRange(startSpecifier, specifierLen)
2209           << Ex->getSourceRange(),
2210         getLocationOfByte(CS.getStart()),
2211         true,
2212         getSpecifierRange(startSpecifier, specifierLen));
2213     }
2214   }
2215 
2216   return true;
2217 }
2218 
2219 //===--- CHECK: Scanf format string checking ------------------------------===//
2220 
2221 namespace {
2222 class CheckScanfHandler : public CheckFormatHandler {
2223 public:
2224   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2225                     const Expr *origFormatExpr, unsigned firstDataArg,
2226                     unsigned numDataArgs, bool isObjCLiteral,
2227                     const char *beg, bool hasVAListArg,
2228                     Expr **Args, unsigned NumArgs,
2229                     unsigned formatIdx, bool inFunctionCall)
2230   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2231                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
2232                        Args, NumArgs, formatIdx, inFunctionCall) {}
2233 
2234   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2235                             const char *startSpecifier,
2236                             unsigned specifierLen);
2237 
2238   bool HandleInvalidScanfConversionSpecifier(
2239           const analyze_scanf::ScanfSpecifier &FS,
2240           const char *startSpecifier,
2241           unsigned specifierLen);
2242 
2243   void HandleIncompleteScanList(const char *start, const char *end);
2244 };
2245 }
2246 
2247 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2248                                                  const char *end) {
2249   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2250                        getLocationOfByte(end), /*IsStringLocation*/true,
2251                        getSpecifierRange(start, end - start));
2252 }
2253 
2254 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2255                                         const analyze_scanf::ScanfSpecifier &FS,
2256                                         const char *startSpecifier,
2257                                         unsigned specifierLen) {
2258 
2259   const analyze_scanf::ScanfConversionSpecifier &CS =
2260     FS.getConversionSpecifier();
2261 
2262   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2263                                           getLocationOfByte(CS.getStart()),
2264                                           startSpecifier, specifierLen,
2265                                           CS.getStart(), CS.getLength());
2266 }
2267 
2268 bool CheckScanfHandler::HandleScanfSpecifier(
2269                                        const analyze_scanf::ScanfSpecifier &FS,
2270                                        const char *startSpecifier,
2271                                        unsigned specifierLen) {
2272 
2273   using namespace analyze_scanf;
2274   using namespace analyze_format_string;
2275 
2276   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
2277 
2278   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
2279   // be used to decide if we are using positional arguments consistently.
2280   if (FS.consumesDataArgument()) {
2281     if (atFirstArg) {
2282       atFirstArg = false;
2283       usesPositionalArgs = FS.usesPositionalArg();
2284     }
2285     else if (usesPositionalArgs != FS.usesPositionalArg()) {
2286       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2287                                         startSpecifier, specifierLen);
2288       return false;
2289     }
2290   }
2291 
2292   // Check if the field with is non-zero.
2293   const OptionalAmount &Amt = FS.getFieldWidth();
2294   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2295     if (Amt.getConstantAmount() == 0) {
2296       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2297                                                    Amt.getConstantLength());
2298       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2299                            getLocationOfByte(Amt.getStart()),
2300                            /*IsStringLocation*/true, R,
2301                            FixItHint::CreateRemoval(R));
2302     }
2303   }
2304 
2305   if (!FS.consumesDataArgument()) {
2306     // FIXME: Technically specifying a precision or field width here
2307     // makes no sense.  Worth issuing a warning at some point.
2308     return true;
2309   }
2310 
2311   // Consume the argument.
2312   unsigned argIndex = FS.getArgIndex();
2313   if (argIndex < NumDataArgs) {
2314       // The check to see if the argIndex is valid will come later.
2315       // We set the bit here because we may exit early from this
2316       // function if we encounter some other error.
2317     CoveredArgs.set(argIndex);
2318   }
2319 
2320   // Check the length modifier is valid with the given conversion specifier.
2321   const LengthModifier &LM = FS.getLengthModifier();
2322   if (!FS.hasValidLengthModifier()) {
2323     const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2324     EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2325                          << LM.toString() << CS.toString()
2326                          << getSpecifierRange(startSpecifier, specifierLen),
2327                          getLocationOfByte(LM.getStart()),
2328                          /*IsStringLocation*/true, R,
2329                          FixItHint::CreateRemoval(R));
2330   }
2331 
2332   // The remaining checks depend on the data arguments.
2333   if (HasVAListArg)
2334     return true;
2335 
2336   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2337     return false;
2338 
2339   // Check that the argument type matches the format specifier.
2340   const Expr *Ex = getDataArg(argIndex);
2341   const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2342   if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2343     ScanfSpecifier fixedFS = FS;
2344     bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions(),
2345                                    S.Context);
2346 
2347     if (success) {
2348       // Get the fix string from the fixed format specifier.
2349       SmallString<128> buf;
2350       llvm::raw_svector_ostream os(buf);
2351       fixedFS.toString(os);
2352 
2353       EmitFormatDiagnostic(
2354         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2355           << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2356           << Ex->getSourceRange(),
2357         getLocationOfByte(CS.getStart()),
2358         /*IsStringLocation*/true,
2359         getSpecifierRange(startSpecifier, specifierLen),
2360         FixItHint::CreateReplacement(
2361           getSpecifierRange(startSpecifier, specifierLen),
2362           os.str()));
2363     } else {
2364       EmitFormatDiagnostic(
2365         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2366           << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2367           << Ex->getSourceRange(),
2368         getLocationOfByte(CS.getStart()),
2369         /*IsStringLocation*/true,
2370         getSpecifierRange(startSpecifier, specifierLen));
2371     }
2372   }
2373 
2374   return true;
2375 }
2376 
2377 void Sema::CheckFormatString(const StringLiteral *FExpr,
2378                              const Expr *OrigFormatExpr,
2379                              Expr **Args, unsigned NumArgs,
2380                              bool HasVAListArg, unsigned format_idx,
2381                              unsigned firstDataArg, FormatStringType Type,
2382                              bool inFunctionCall) {
2383 
2384   // CHECK: is the format string a wide literal?
2385   if (!FExpr->isAscii()) {
2386     CheckFormatHandler::EmitFormatDiagnostic(
2387       *this, inFunctionCall, Args[format_idx],
2388       PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2389       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
2390     return;
2391   }
2392 
2393   // Str - The format string.  NOTE: this is NOT null-terminated!
2394   StringRef StrRef = FExpr->getString();
2395   const char *Str = StrRef.data();
2396   unsigned StrLen = StrRef.size();
2397   const unsigned numDataArgs = NumArgs - firstDataArg;
2398 
2399   // CHECK: empty format string?
2400   if (StrLen == 0 && numDataArgs > 0) {
2401     CheckFormatHandler::EmitFormatDiagnostic(
2402       *this, inFunctionCall, Args[format_idx],
2403       PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2404       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
2405     return;
2406   }
2407 
2408   if (Type == FST_Printf || Type == FST_NSString) {
2409     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2410                          numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2411                          Str, HasVAListArg, Args, NumArgs, format_idx,
2412                          inFunctionCall);
2413 
2414     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
2415                                                   getLangOptions()))
2416       H.DoneProcessing();
2417   } else if (Type == FST_Scanf) {
2418     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2419                         numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2420                         Str, HasVAListArg, Args, NumArgs, format_idx,
2421                         inFunctionCall);
2422 
2423     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
2424                                                  getLangOptions()))
2425       H.DoneProcessing();
2426   } // TODO: handle other formats
2427 }
2428 
2429 //===--- CHECK: Standard memory functions ---------------------------------===//
2430 
2431 /// \brief Determine whether the given type is a dynamic class type (e.g.,
2432 /// whether it has a vtable).
2433 static bool isDynamicClassType(QualType T) {
2434   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2435     if (CXXRecordDecl *Definition = Record->getDefinition())
2436       if (Definition->isDynamicClass())
2437         return true;
2438 
2439   return false;
2440 }
2441 
2442 /// \brief If E is a sizeof expression, returns its argument expression,
2443 /// otherwise returns NULL.
2444 static const Expr *getSizeOfExprArg(const Expr* E) {
2445   if (const UnaryExprOrTypeTraitExpr *SizeOf =
2446       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2447     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2448       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
2449 
2450   return 0;
2451 }
2452 
2453 /// \brief If E is a sizeof expression, returns its argument type.
2454 static QualType getSizeOfArgType(const Expr* E) {
2455   if (const UnaryExprOrTypeTraitExpr *SizeOf =
2456       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2457     if (SizeOf->getKind() == clang::UETT_SizeOf)
2458       return SizeOf->getTypeOfArgument();
2459 
2460   return QualType();
2461 }
2462 
2463 /// \brief Check for dangerous or invalid arguments to memset().
2464 ///
2465 /// This issues warnings on known problematic, dangerous or unspecified
2466 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2467 /// function calls.
2468 ///
2469 /// \param Call The call expression to diagnose.
2470 void Sema::CheckMemaccessArguments(const CallExpr *Call,
2471                                    unsigned BId,
2472                                    IdentifierInfo *FnName) {
2473   assert(BId != 0);
2474 
2475   // It is possible to have a non-standard definition of memset.  Validate
2476   // we have enough arguments, and if not, abort further checking.
2477   unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
2478   if (Call->getNumArgs() < ExpectedNumArgs)
2479     return;
2480 
2481   unsigned LastArg = (BId == Builtin::BImemset ||
2482                       BId == Builtin::BIstrndup ? 1 : 2);
2483   unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
2484   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
2485 
2486   // We have special checking when the length is a sizeof expression.
2487   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2488   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2489   llvm::FoldingSetNodeID SizeOfArgID;
2490 
2491   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2492     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
2493     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
2494 
2495     QualType DestTy = Dest->getType();
2496     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2497       QualType PointeeTy = DestPtrTy->getPointeeType();
2498 
2499       // Never warn about void type pointers. This can be used to suppress
2500       // false positives.
2501       if (PointeeTy->isVoidType())
2502         continue;
2503 
2504       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2505       // actually comparing the expressions for equality. Because computing the
2506       // expression IDs can be expensive, we only do this if the diagnostic is
2507       // enabled.
2508       if (SizeOfArg &&
2509           Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2510                                    SizeOfArg->getExprLoc())) {
2511         // We only compute IDs for expressions if the warning is enabled, and
2512         // cache the sizeof arg's ID.
2513         if (SizeOfArgID == llvm::FoldingSetNodeID())
2514           SizeOfArg->Profile(SizeOfArgID, Context, true);
2515         llvm::FoldingSetNodeID DestID;
2516         Dest->Profile(DestID, Context, true);
2517         if (DestID == SizeOfArgID) {
2518           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2519           //       over sizeof(src) as well.
2520           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2521           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2522             if (UnaryOp->getOpcode() == UO_AddrOf)
2523               ActionIdx = 1; // If its an address-of operator, just remove it.
2524           if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2525             ActionIdx = 2; // If the pointee's size is sizeof(char),
2526                            // suggest an explicit length.
2527           unsigned DestSrcSelect =
2528             (BId == Builtin::BIstrndup ? 1 : ArgIdx);
2529           DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2530                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
2531                                 << FnName << DestSrcSelect << ActionIdx
2532                                 << Dest->getSourceRange()
2533                                 << SizeOfArg->getSourceRange());
2534           break;
2535         }
2536       }
2537 
2538       // Also check for cases where the sizeof argument is the exact same
2539       // type as the memory argument, and where it points to a user-defined
2540       // record type.
2541       if (SizeOfArgTy != QualType()) {
2542         if (PointeeTy->isRecordType() &&
2543             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2544           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2545                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
2546                                 << FnName << SizeOfArgTy << ArgIdx
2547                                 << PointeeTy << Dest->getSourceRange()
2548                                 << LenExpr->getSourceRange());
2549           break;
2550         }
2551       }
2552 
2553       // Always complain about dynamic classes.
2554       if (isDynamicClassType(PointeeTy)) {
2555 
2556         unsigned OperationType = 0;
2557         // "overwritten" if we're warning about the destination for any call
2558         // but memcmp; otherwise a verb appropriate to the call.
2559         if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2560           if (BId == Builtin::BImemcpy)
2561             OperationType = 1;
2562           else if(BId == Builtin::BImemmove)
2563             OperationType = 2;
2564           else if (BId == Builtin::BImemcmp)
2565             OperationType = 3;
2566         }
2567 
2568         DiagRuntimeBehavior(
2569           Dest->getExprLoc(), Dest,
2570           PDiag(diag::warn_dyn_class_memaccess)
2571             << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
2572             << FnName << PointeeTy
2573             << OperationType
2574             << Call->getCallee()->getSourceRange());
2575       } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2576                BId != Builtin::BImemset)
2577         DiagRuntimeBehavior(
2578           Dest->getExprLoc(), Dest,
2579           PDiag(diag::warn_arc_object_memaccess)
2580             << ArgIdx << FnName << PointeeTy
2581             << Call->getCallee()->getSourceRange());
2582       else
2583         continue;
2584 
2585       DiagRuntimeBehavior(
2586         Dest->getExprLoc(), Dest,
2587         PDiag(diag::note_bad_memaccess_silence)
2588           << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2589       break;
2590     }
2591   }
2592 }
2593 
2594 // A little helper routine: ignore addition and subtraction of integer literals.
2595 // This intentionally does not ignore all integer constant expressions because
2596 // we don't want to remove sizeof().
2597 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2598   Ex = Ex->IgnoreParenCasts();
2599 
2600   for (;;) {
2601     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2602     if (!BO || !BO->isAdditiveOp())
2603       break;
2604 
2605     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2606     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2607 
2608     if (isa<IntegerLiteral>(RHS))
2609       Ex = LHS;
2610     else if (isa<IntegerLiteral>(LHS))
2611       Ex = RHS;
2612     else
2613       break;
2614   }
2615 
2616   return Ex;
2617 }
2618 
2619 // Warn if the user has made the 'size' argument to strlcpy or strlcat
2620 // be the size of the source, instead of the destination.
2621 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2622                                     IdentifierInfo *FnName) {
2623 
2624   // Don't crash if the user has the wrong number of arguments
2625   if (Call->getNumArgs() != 3)
2626     return;
2627 
2628   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2629   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2630   const Expr *CompareWithSrc = NULL;
2631 
2632   // Look for 'strlcpy(dst, x, sizeof(x))'
2633   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2634     CompareWithSrc = Ex;
2635   else {
2636     // Look for 'strlcpy(dst, x, strlen(x))'
2637     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2638       if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
2639           && SizeCall->getNumArgs() == 1)
2640         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2641     }
2642   }
2643 
2644   if (!CompareWithSrc)
2645     return;
2646 
2647   // Determine if the argument to sizeof/strlen is equal to the source
2648   // argument.  In principle there's all kinds of things you could do
2649   // here, for instance creating an == expression and evaluating it with
2650   // EvaluateAsBooleanCondition, but this uses a more direct technique:
2651   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2652   if (!SrcArgDRE)
2653     return;
2654 
2655   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2656   if (!CompareWithSrcDRE ||
2657       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2658     return;
2659 
2660   const Expr *OriginalSizeArg = Call->getArg(2);
2661   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2662     << OriginalSizeArg->getSourceRange() << FnName;
2663 
2664   // Output a FIXIT hint if the destination is an array (rather than a
2665   // pointer to an array).  This could be enhanced to handle some
2666   // pointers if we know the actual size, like if DstArg is 'array+2'
2667   // we could say 'sizeof(array)-2'.
2668   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
2669   QualType DstArgTy = DstArg->getType();
2670 
2671   // Only handle constant-sized or VLAs, but not flexible members.
2672   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2673     // Only issue the FIXIT for arrays of size > 1.
2674     if (CAT->getSize().getSExtValue() <= 1)
2675       return;
2676   } else if (!DstArgTy->isVariableArrayType()) {
2677     return;
2678   }
2679 
2680   SmallString<128> sizeString;
2681   llvm::raw_svector_ostream OS(sizeString);
2682   OS << "sizeof(";
2683   DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2684   OS << ")";
2685 
2686   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2687     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2688                                     OS.str());
2689 }
2690 
2691 /// Check if two expressions refer to the same declaration.
2692 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
2693   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
2694     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
2695       return D1->getDecl() == D2->getDecl();
2696   return false;
2697 }
2698 
2699 static const Expr *getStrlenExprArg(const Expr *E) {
2700   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2701     const FunctionDecl *FD = CE->getDirectCallee();
2702     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
2703       return 0;
2704     return CE->getArg(0)->IgnoreParenCasts();
2705   }
2706   return 0;
2707 }
2708 
2709 // Warn on anti-patterns as the 'size' argument to strncat.
2710 // The correct size argument should look like following:
2711 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
2712 void Sema::CheckStrncatArguments(const CallExpr *CE,
2713                                  IdentifierInfo *FnName) {
2714   // Don't crash if the user has the wrong number of arguments.
2715   if (CE->getNumArgs() < 3)
2716     return;
2717   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
2718   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
2719   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
2720 
2721   // Identify common expressions, which are wrongly used as the size argument
2722   // to strncat and may lead to buffer overflows.
2723   unsigned PatternType = 0;
2724   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
2725     // - sizeof(dst)
2726     if (referToTheSameDecl(SizeOfArg, DstArg))
2727       PatternType = 1;
2728     // - sizeof(src)
2729     else if (referToTheSameDecl(SizeOfArg, SrcArg))
2730       PatternType = 2;
2731   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
2732     if (BE->getOpcode() == BO_Sub) {
2733       const Expr *L = BE->getLHS()->IgnoreParenCasts();
2734       const Expr *R = BE->getRHS()->IgnoreParenCasts();
2735       // - sizeof(dst) - strlen(dst)
2736       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
2737           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
2738         PatternType = 1;
2739       // - sizeof(src) - (anything)
2740       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
2741         PatternType = 2;
2742     }
2743   }
2744 
2745   if (PatternType == 0)
2746     return;
2747 
2748   // Generate the diagnostic.
2749   SourceLocation SL = LenArg->getLocStart();
2750   SourceRange SR = LenArg->getSourceRange();
2751   SourceManager &SM  = PP.getSourceManager();
2752 
2753   // If the function is defined as a builtin macro, do not show macro expansion.
2754   if (SM.isMacroArgExpansion(SL)) {
2755     SL = SM.getSpellingLoc(SL);
2756     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
2757                      SM.getSpellingLoc(SR.getEnd()));
2758   }
2759 
2760   if (PatternType == 1)
2761     Diag(SL, diag::warn_strncat_large_size) << SR;
2762   else
2763     Diag(SL, diag::warn_strncat_src_size) << SR;
2764 
2765   // Output a FIXIT hint if the destination is an array (rather than a
2766   // pointer to an array).  This could be enhanced to handle some
2767   // pointers if we know the actual size, like if DstArg is 'array+2'
2768   // we could say 'sizeof(array)-2'.
2769   QualType DstArgTy = DstArg->getType();
2770 
2771   // Only handle constant-sized or VLAs, but not flexible members.
2772   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2773     // Only issue the FIXIT for arrays of size > 1.
2774     if (CAT->getSize().getSExtValue() <= 1)
2775       return;
2776   } else if (!DstArgTy->isVariableArrayType()) {
2777     return;
2778   }
2779 
2780   SmallString<128> sizeString;
2781   llvm::raw_svector_ostream OS(sizeString);
2782   OS << "sizeof(";
2783   DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2784   OS << ") - ";
2785   OS << "strlen(";
2786   DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2787   OS << ") - 1";
2788 
2789   Diag(SL, diag::note_strncat_wrong_size)
2790     << FixItHint::CreateReplacement(SR, OS.str());
2791 }
2792 
2793 //===--- CHECK: Return Address of Stack Variable --------------------------===//
2794 
2795 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2796 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
2797 
2798 /// CheckReturnStackAddr - Check if a return statement returns the address
2799 ///   of a stack variable.
2800 void
2801 Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2802                            SourceLocation ReturnLoc) {
2803 
2804   Expr *stackE = 0;
2805   SmallVector<DeclRefExpr *, 8> refVars;
2806 
2807   // Perform checking for returned stack addresses, local blocks,
2808   // label addresses or references to temporaries.
2809   if (lhsType->isPointerType() ||
2810       (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
2811     stackE = EvalAddr(RetValExp, refVars);
2812   } else if (lhsType->isReferenceType()) {
2813     stackE = EvalVal(RetValExp, refVars);
2814   }
2815 
2816   if (stackE == 0)
2817     return; // Nothing suspicious was found.
2818 
2819   SourceLocation diagLoc;
2820   SourceRange diagRange;
2821   if (refVars.empty()) {
2822     diagLoc = stackE->getLocStart();
2823     diagRange = stackE->getSourceRange();
2824   } else {
2825     // We followed through a reference variable. 'stackE' contains the
2826     // problematic expression but we will warn at the return statement pointing
2827     // at the reference variable. We will later display the "trail" of
2828     // reference variables using notes.
2829     diagLoc = refVars[0]->getLocStart();
2830     diagRange = refVars[0]->getSourceRange();
2831   }
2832 
2833   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2834     Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2835                                              : diag::warn_ret_stack_addr)
2836      << DR->getDecl()->getDeclName() << diagRange;
2837   } else if (isa<BlockExpr>(stackE)) { // local block.
2838     Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2839   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2840     Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2841   } else { // local temporary.
2842     Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2843                                              : diag::warn_ret_local_temp_addr)
2844      << diagRange;
2845   }
2846 
2847   // Display the "trail" of reference variables that we followed until we
2848   // found the problematic expression using notes.
2849   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2850     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2851     // If this var binds to another reference var, show the range of the next
2852     // var, otherwise the var binds to the problematic expression, in which case
2853     // show the range of the expression.
2854     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2855                                   : stackE->getSourceRange();
2856     Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2857       << VD->getDeclName() << range;
2858   }
2859 }
2860 
2861 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2862 ///  check if the expression in a return statement evaluates to an address
2863 ///  to a location on the stack, a local block, an address of a label, or a
2864 ///  reference to local temporary. The recursion is used to traverse the
2865 ///  AST of the return expression, with recursion backtracking when we
2866 ///  encounter a subexpression that (1) clearly does not lead to one of the
2867 ///  above problematic expressions (2) is something we cannot determine leads to
2868 ///  a problematic expression based on such local checking.
2869 ///
2870 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
2871 ///  the expression that they point to. Such variables are added to the
2872 ///  'refVars' vector so that we know what the reference variable "trail" was.
2873 ///
2874 ///  EvalAddr processes expressions that are pointers that are used as
2875 ///  references (and not L-values).  EvalVal handles all other values.
2876 ///  At the base case of the recursion is a check for the above problematic
2877 ///  expressions.
2878 ///
2879 ///  This implementation handles:
2880 ///
2881 ///   * pointer-to-pointer casts
2882 ///   * implicit conversions from array references to pointers
2883 ///   * taking the address of fields
2884 ///   * arbitrary interplay between "&" and "*" operators
2885 ///   * pointer arithmetic from an address of a stack variable
2886 ///   * taking the address of an array element where the array is on the stack
2887 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2888   if (E->isTypeDependent())
2889       return NULL;
2890 
2891   // We should only be called for evaluating pointer expressions.
2892   assert((E->getType()->isAnyPointerType() ||
2893           E->getType()->isBlockPointerType() ||
2894           E->getType()->isObjCQualifiedIdType()) &&
2895          "EvalAddr only works on pointers");
2896 
2897   E = E->IgnoreParens();
2898 
2899   // Our "symbolic interpreter" is just a dispatch off the currently
2900   // viewed AST node.  We then recursively traverse the AST by calling
2901   // EvalAddr and EvalVal appropriately.
2902   switch (E->getStmtClass()) {
2903   case Stmt::DeclRefExprClass: {
2904     DeclRefExpr *DR = cast<DeclRefExpr>(E);
2905 
2906     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2907       // If this is a reference variable, follow through to the expression that
2908       // it points to.
2909       if (V->hasLocalStorage() &&
2910           V->getType()->isReferenceType() && V->hasInit()) {
2911         // Add the reference variable to the "trail".
2912         refVars.push_back(DR);
2913         return EvalAddr(V->getInit(), refVars);
2914       }
2915 
2916     return NULL;
2917   }
2918 
2919   case Stmt::UnaryOperatorClass: {
2920     // The only unary operator that make sense to handle here
2921     // is AddrOf.  All others don't make sense as pointers.
2922     UnaryOperator *U = cast<UnaryOperator>(E);
2923 
2924     if (U->getOpcode() == UO_AddrOf)
2925       return EvalVal(U->getSubExpr(), refVars);
2926     else
2927       return NULL;
2928   }
2929 
2930   case Stmt::BinaryOperatorClass: {
2931     // Handle pointer arithmetic.  All other binary operators are not valid
2932     // in this context.
2933     BinaryOperator *B = cast<BinaryOperator>(E);
2934     BinaryOperatorKind op = B->getOpcode();
2935 
2936     if (op != BO_Add && op != BO_Sub)
2937       return NULL;
2938 
2939     Expr *Base = B->getLHS();
2940 
2941     // Determine which argument is the real pointer base.  It could be
2942     // the RHS argument instead of the LHS.
2943     if (!Base->getType()->isPointerType()) Base = B->getRHS();
2944 
2945     assert (Base->getType()->isPointerType());
2946     return EvalAddr(Base, refVars);
2947   }
2948 
2949   // For conditional operators we need to see if either the LHS or RHS are
2950   // valid DeclRefExpr*s.  If one of them is valid, we return it.
2951   case Stmt::ConditionalOperatorClass: {
2952     ConditionalOperator *C = cast<ConditionalOperator>(E);
2953 
2954     // Handle the GNU extension for missing LHS.
2955     if (Expr *lhsExpr = C->getLHS()) {
2956     // In C++, we can have a throw-expression, which has 'void' type.
2957       if (!lhsExpr->getType()->isVoidType())
2958         if (Expr* LHS = EvalAddr(lhsExpr, refVars))
2959           return LHS;
2960     }
2961 
2962     // In C++, we can have a throw-expression, which has 'void' type.
2963     if (C->getRHS()->getType()->isVoidType())
2964       return NULL;
2965 
2966     return EvalAddr(C->getRHS(), refVars);
2967   }
2968 
2969   case Stmt::BlockExprClass:
2970     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
2971       return E; // local block.
2972     return NULL;
2973 
2974   case Stmt::AddrLabelExprClass:
2975     return E; // address of label.
2976 
2977   case Stmt::ExprWithCleanupsClass:
2978     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2979 
2980   // For casts, we need to handle conversions from arrays to
2981   // pointer values, and pointer-to-pointer conversions.
2982   case Stmt::ImplicitCastExprClass:
2983   case Stmt::CStyleCastExprClass:
2984   case Stmt::CXXFunctionalCastExprClass:
2985   case Stmt::ObjCBridgedCastExprClass: {
2986     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2987     QualType T = SubExpr->getType();
2988 
2989     if (SubExpr->getType()->isPointerType() ||
2990         SubExpr->getType()->isBlockPointerType() ||
2991         SubExpr->getType()->isObjCQualifiedIdType())
2992       return EvalAddr(SubExpr, refVars);
2993     else if (T->isArrayType())
2994       return EvalVal(SubExpr, refVars);
2995     else
2996       return 0;
2997   }
2998 
2999   // C++ casts.  For dynamic casts, static casts, and const casts, we
3000   // are always converting from a pointer-to-pointer, so we just blow
3001   // through the cast.  In the case the dynamic cast doesn't fail (and
3002   // return NULL), we take the conservative route and report cases
3003   // where we return the address of a stack variable.  For Reinterpre
3004   // FIXME: The comment about is wrong; we're not always converting
3005   // from pointer to pointer. I'm guessing that this code should also
3006   // handle references to objects.
3007   case Stmt::CXXStaticCastExprClass:
3008   case Stmt::CXXDynamicCastExprClass:
3009   case Stmt::CXXConstCastExprClass:
3010   case Stmt::CXXReinterpretCastExprClass: {
3011       Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
3012       if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
3013         return EvalAddr(S, refVars);
3014       else
3015         return NULL;
3016   }
3017 
3018   case Stmt::MaterializeTemporaryExprClass:
3019     if (Expr *Result = EvalAddr(
3020                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3021                                 refVars))
3022       return Result;
3023 
3024     return E;
3025 
3026   // Everything else: we simply don't reason about them.
3027   default:
3028     return NULL;
3029   }
3030 }
3031 
3032 
3033 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
3034 ///   See the comments for EvalAddr for more details.
3035 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
3036 do {
3037   // We should only be called for evaluating non-pointer expressions, or
3038   // expressions with a pointer type that are not used as references but instead
3039   // are l-values (e.g., DeclRefExpr with a pointer type).
3040 
3041   // Our "symbolic interpreter" is just a dispatch off the currently
3042   // viewed AST node.  We then recursively traverse the AST by calling
3043   // EvalAddr and EvalVal appropriately.
3044 
3045   E = E->IgnoreParens();
3046   switch (E->getStmtClass()) {
3047   case Stmt::ImplicitCastExprClass: {
3048     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
3049     if (IE->getValueKind() == VK_LValue) {
3050       E = IE->getSubExpr();
3051       continue;
3052     }
3053     return NULL;
3054   }
3055 
3056   case Stmt::ExprWithCleanupsClass:
3057     return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
3058 
3059   case Stmt::DeclRefExprClass: {
3060     // When we hit a DeclRefExpr we are looking at code that refers to a
3061     // variable's name. If it's not a reference variable we check if it has
3062     // local storage within the function, and if so, return the expression.
3063     DeclRefExpr *DR = cast<DeclRefExpr>(E);
3064 
3065     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3066       if (V->hasLocalStorage()) {
3067         if (!V->getType()->isReferenceType())
3068           return DR;
3069 
3070         // Reference variable, follow through to the expression that
3071         // it points to.
3072         if (V->hasInit()) {
3073           // Add the reference variable to the "trail".
3074           refVars.push_back(DR);
3075           return EvalVal(V->getInit(), refVars);
3076         }
3077       }
3078 
3079     return NULL;
3080   }
3081 
3082   case Stmt::UnaryOperatorClass: {
3083     // The only unary operator that make sense to handle here
3084     // is Deref.  All others don't resolve to a "name."  This includes
3085     // handling all sorts of rvalues passed to a unary operator.
3086     UnaryOperator *U = cast<UnaryOperator>(E);
3087 
3088     if (U->getOpcode() == UO_Deref)
3089       return EvalAddr(U->getSubExpr(), refVars);
3090 
3091     return NULL;
3092   }
3093 
3094   case Stmt::ArraySubscriptExprClass: {
3095     // Array subscripts are potential references to data on the stack.  We
3096     // retrieve the DeclRefExpr* for the array variable if it indeed
3097     // has local storage.
3098     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
3099   }
3100 
3101   case Stmt::ConditionalOperatorClass: {
3102     // For conditional operators we need to see if either the LHS or RHS are
3103     // non-NULL Expr's.  If one is non-NULL, we return it.
3104     ConditionalOperator *C = cast<ConditionalOperator>(E);
3105 
3106     // Handle the GNU extension for missing LHS.
3107     if (Expr *lhsExpr = C->getLHS())
3108       if (Expr *LHS = EvalVal(lhsExpr, refVars))
3109         return LHS;
3110 
3111     return EvalVal(C->getRHS(), refVars);
3112   }
3113 
3114   // Accesses to members are potential references to data on the stack.
3115   case Stmt::MemberExprClass: {
3116     MemberExpr *M = cast<MemberExpr>(E);
3117 
3118     // Check for indirect access.  We only want direct field accesses.
3119     if (M->isArrow())
3120       return NULL;
3121 
3122     // Check whether the member type is itself a reference, in which case
3123     // we're not going to refer to the member, but to what the member refers to.
3124     if (M->getMemberDecl()->getType()->isReferenceType())
3125       return NULL;
3126 
3127     return EvalVal(M->getBase(), refVars);
3128   }
3129 
3130   case Stmt::MaterializeTemporaryExprClass:
3131     if (Expr *Result = EvalVal(
3132                           cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3133                                refVars))
3134       return Result;
3135 
3136     return E;
3137 
3138   default:
3139     // Check that we don't return or take the address of a reference to a
3140     // temporary. This is only useful in C++.
3141     if (!E->isTypeDependent() && E->isRValue())
3142       return E;
3143 
3144     // Everything else: we simply don't reason about them.
3145     return NULL;
3146   }
3147 } while (true);
3148 }
3149 
3150 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3151 
3152 /// Check for comparisons of floating point operands using != and ==.
3153 /// Issue a warning if these are no self-comparisons, as they are not likely
3154 /// to do what the programmer intended.
3155 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
3156   bool EmitWarning = true;
3157 
3158   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3159   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
3160 
3161   // Special case: check for x == x (which is OK).
3162   // Do not emit warnings for such cases.
3163   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3164     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3165       if (DRL->getDecl() == DRR->getDecl())
3166         EmitWarning = false;
3167 
3168 
3169   // Special case: check for comparisons against literals that can be exactly
3170   //  represented by APFloat.  In such cases, do not emit a warning.  This
3171   //  is a heuristic: often comparison against such literals are used to
3172   //  detect if a value in a variable has not changed.  This clearly can
3173   //  lead to false negatives.
3174   if (EmitWarning) {
3175     if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3176       if (FLL->isExact())
3177         EmitWarning = false;
3178     } else
3179       if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3180         if (FLR->isExact())
3181           EmitWarning = false;
3182     }
3183   }
3184 
3185   // Check for comparisons with builtin types.
3186   if (EmitWarning)
3187     if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3188       if (CL->isBuiltinCall())
3189         EmitWarning = false;
3190 
3191   if (EmitWarning)
3192     if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3193       if (CR->isBuiltinCall())
3194         EmitWarning = false;
3195 
3196   // Emit the diagnostic.
3197   if (EmitWarning)
3198     Diag(Loc, diag::warn_floatingpoint_eq)
3199       << LHS->getSourceRange() << RHS->getSourceRange();
3200 }
3201 
3202 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3203 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
3204 
3205 namespace {
3206 
3207 /// Structure recording the 'active' range of an integer-valued
3208 /// expression.
3209 struct IntRange {
3210   /// The number of bits active in the int.
3211   unsigned Width;
3212 
3213   /// True if the int is known not to have negative values.
3214   bool NonNegative;
3215 
3216   IntRange(unsigned Width, bool NonNegative)
3217     : Width(Width), NonNegative(NonNegative)
3218   {}
3219 
3220   /// Returns the range of the bool type.
3221   static IntRange forBoolType() {
3222     return IntRange(1, true);
3223   }
3224 
3225   /// Returns the range of an opaque value of the given integral type.
3226   static IntRange forValueOfType(ASTContext &C, QualType T) {
3227     return forValueOfCanonicalType(C,
3228                           T->getCanonicalTypeInternal().getTypePtr());
3229   }
3230 
3231   /// Returns the range of an opaque value of a canonical integral type.
3232   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
3233     assert(T->isCanonicalUnqualified());
3234 
3235     if (const VectorType *VT = dyn_cast<VectorType>(T))
3236       T = VT->getElementType().getTypePtr();
3237     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3238       T = CT->getElementType().getTypePtr();
3239 
3240     // For enum types, use the known bit width of the enumerators.
3241     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3242       EnumDecl *Enum = ET->getDecl();
3243       if (!Enum->isCompleteDefinition())
3244         return IntRange(C.getIntWidth(QualType(T, 0)), false);
3245 
3246       unsigned NumPositive = Enum->getNumPositiveBits();
3247       unsigned NumNegative = Enum->getNumNegativeBits();
3248 
3249       return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3250     }
3251 
3252     const BuiltinType *BT = cast<BuiltinType>(T);
3253     assert(BT->isInteger());
3254 
3255     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3256   }
3257 
3258   /// Returns the "target" range of a canonical integral type, i.e.
3259   /// the range of values expressible in the type.
3260   ///
3261   /// This matches forValueOfCanonicalType except that enums have the
3262   /// full range of their type, not the range of their enumerators.
3263   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3264     assert(T->isCanonicalUnqualified());
3265 
3266     if (const VectorType *VT = dyn_cast<VectorType>(T))
3267       T = VT->getElementType().getTypePtr();
3268     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3269       T = CT->getElementType().getTypePtr();
3270     if (const EnumType *ET = dyn_cast<EnumType>(T))
3271       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
3272 
3273     const BuiltinType *BT = cast<BuiltinType>(T);
3274     assert(BT->isInteger());
3275 
3276     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3277   }
3278 
3279   /// Returns the supremum of two ranges: i.e. their conservative merge.
3280   static IntRange join(IntRange L, IntRange R) {
3281     return IntRange(std::max(L.Width, R.Width),
3282                     L.NonNegative && R.NonNegative);
3283   }
3284 
3285   /// Returns the infinum of two ranges: i.e. their aggressive merge.
3286   static IntRange meet(IntRange L, IntRange R) {
3287     return IntRange(std::min(L.Width, R.Width),
3288                     L.NonNegative || R.NonNegative);
3289   }
3290 };
3291 
3292 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3293                               unsigned MaxWidth) {
3294   if (value.isSigned() && value.isNegative())
3295     return IntRange(value.getMinSignedBits(), false);
3296 
3297   if (value.getBitWidth() > MaxWidth)
3298     value = value.trunc(MaxWidth);
3299 
3300   // isNonNegative() just checks the sign bit without considering
3301   // signedness.
3302   return IntRange(value.getActiveBits(), true);
3303 }
3304 
3305 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3306                               unsigned MaxWidth) {
3307   if (result.isInt())
3308     return GetValueRange(C, result.getInt(), MaxWidth);
3309 
3310   if (result.isVector()) {
3311     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3312     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3313       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3314       R = IntRange::join(R, El);
3315     }
3316     return R;
3317   }
3318 
3319   if (result.isComplexInt()) {
3320     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3321     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3322     return IntRange::join(R, I);
3323   }
3324 
3325   // This can happen with lossless casts to intptr_t of "based" lvalues.
3326   // Assume it might use arbitrary bits.
3327   // FIXME: The only reason we need to pass the type in here is to get
3328   // the sign right on this one case.  It would be nice if APValue
3329   // preserved this.
3330   assert(result.isLValue() || result.isAddrLabelDiff());
3331   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
3332 }
3333 
3334 /// Pseudo-evaluate the given integer expression, estimating the
3335 /// range of values it might take.
3336 ///
3337 /// \param MaxWidth - the width to which the value will be truncated
3338 static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3339   E = E->IgnoreParens();
3340 
3341   // Try a full evaluation first.
3342   Expr::EvalResult result;
3343   if (E->EvaluateAsRValue(result, C))
3344     return GetValueRange(C, result.Val, E->getType(), MaxWidth);
3345 
3346   // I think we only want to look through implicit casts here; if the
3347   // user has an explicit widening cast, we should treat the value as
3348   // being of the new, wider type.
3349   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
3350     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
3351       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3352 
3353     IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
3354 
3355     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
3356 
3357     // Assume that non-integer casts can span the full range of the type.
3358     if (!isIntegerCast)
3359       return OutputTypeRange;
3360 
3361     IntRange SubRange
3362       = GetExprRange(C, CE->getSubExpr(),
3363                      std::min(MaxWidth, OutputTypeRange.Width));
3364 
3365     // Bail out if the subexpr's range is as wide as the cast type.
3366     if (SubRange.Width >= OutputTypeRange.Width)
3367       return OutputTypeRange;
3368 
3369     // Otherwise, we take the smaller width, and we're non-negative if
3370     // either the output type or the subexpr is.
3371     return IntRange(SubRange.Width,
3372                     SubRange.NonNegative || OutputTypeRange.NonNegative);
3373   }
3374 
3375   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3376     // If we can fold the condition, just take that operand.
3377     bool CondResult;
3378     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3379       return GetExprRange(C, CondResult ? CO->getTrueExpr()
3380                                         : CO->getFalseExpr(),
3381                           MaxWidth);
3382 
3383     // Otherwise, conservatively merge.
3384     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3385     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3386     return IntRange::join(L, R);
3387   }
3388 
3389   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3390     switch (BO->getOpcode()) {
3391 
3392     // Boolean-valued operations are single-bit and positive.
3393     case BO_LAnd:
3394     case BO_LOr:
3395     case BO_LT:
3396     case BO_GT:
3397     case BO_LE:
3398     case BO_GE:
3399     case BO_EQ:
3400     case BO_NE:
3401       return IntRange::forBoolType();
3402 
3403     // The type of the assignments is the type of the LHS, so the RHS
3404     // is not necessarily the same type.
3405     case BO_MulAssign:
3406     case BO_DivAssign:
3407     case BO_RemAssign:
3408     case BO_AddAssign:
3409     case BO_SubAssign:
3410     case BO_XorAssign:
3411     case BO_OrAssign:
3412       // TODO: bitfields?
3413       return IntRange::forValueOfType(C, E->getType());
3414 
3415     // Simple assignments just pass through the RHS, which will have
3416     // been coerced to the LHS type.
3417     case BO_Assign:
3418       // TODO: bitfields?
3419       return GetExprRange(C, BO->getRHS(), MaxWidth);
3420 
3421     // Operations with opaque sources are black-listed.
3422     case BO_PtrMemD:
3423     case BO_PtrMemI:
3424       return IntRange::forValueOfType(C, E->getType());
3425 
3426     // Bitwise-and uses the *infinum* of the two source ranges.
3427     case BO_And:
3428     case BO_AndAssign:
3429       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3430                             GetExprRange(C, BO->getRHS(), MaxWidth));
3431 
3432     // Left shift gets black-listed based on a judgement call.
3433     case BO_Shl:
3434       // ...except that we want to treat '1 << (blah)' as logically
3435       // positive.  It's an important idiom.
3436       if (IntegerLiteral *I
3437             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3438         if (I->getValue() == 1) {
3439           IntRange R = IntRange::forValueOfType(C, E->getType());
3440           return IntRange(R.Width, /*NonNegative*/ true);
3441         }
3442       }
3443       // fallthrough
3444 
3445     case BO_ShlAssign:
3446       return IntRange::forValueOfType(C, E->getType());
3447 
3448     // Right shift by a constant can narrow its left argument.
3449     case BO_Shr:
3450     case BO_ShrAssign: {
3451       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3452 
3453       // If the shift amount is a positive constant, drop the width by
3454       // that much.
3455       llvm::APSInt shift;
3456       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3457           shift.isNonNegative()) {
3458         unsigned zext = shift.getZExtValue();
3459         if (zext >= L.Width)
3460           L.Width = (L.NonNegative ? 0 : 1);
3461         else
3462           L.Width -= zext;
3463       }
3464 
3465       return L;
3466     }
3467 
3468     // Comma acts as its right operand.
3469     case BO_Comma:
3470       return GetExprRange(C, BO->getRHS(), MaxWidth);
3471 
3472     // Black-list pointer subtractions.
3473     case BO_Sub:
3474       if (BO->getLHS()->getType()->isPointerType())
3475         return IntRange::forValueOfType(C, E->getType());
3476       break;
3477 
3478     // The width of a division result is mostly determined by the size
3479     // of the LHS.
3480     case BO_Div: {
3481       // Don't 'pre-truncate' the operands.
3482       unsigned opWidth = C.getIntWidth(E->getType());
3483       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3484 
3485       // If the divisor is constant, use that.
3486       llvm::APSInt divisor;
3487       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3488         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3489         if (log2 >= L.Width)
3490           L.Width = (L.NonNegative ? 0 : 1);
3491         else
3492           L.Width = std::min(L.Width - log2, MaxWidth);
3493         return L;
3494       }
3495 
3496       // Otherwise, just use the LHS's width.
3497       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3498       return IntRange(L.Width, L.NonNegative && R.NonNegative);
3499     }
3500 
3501     // The result of a remainder can't be larger than the result of
3502     // either side.
3503     case BO_Rem: {
3504       // Don't 'pre-truncate' the operands.
3505       unsigned opWidth = C.getIntWidth(E->getType());
3506       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3507       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3508 
3509       IntRange meet = IntRange::meet(L, R);
3510       meet.Width = std::min(meet.Width, MaxWidth);
3511       return meet;
3512     }
3513 
3514     // The default behavior is okay for these.
3515     case BO_Mul:
3516     case BO_Add:
3517     case BO_Xor:
3518     case BO_Or:
3519       break;
3520     }
3521 
3522     // The default case is to treat the operation as if it were closed
3523     // on the narrowest type that encompasses both operands.
3524     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3525     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3526     return IntRange::join(L, R);
3527   }
3528 
3529   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3530     switch (UO->getOpcode()) {
3531     // Boolean-valued operations are white-listed.
3532     case UO_LNot:
3533       return IntRange::forBoolType();
3534 
3535     // Operations with opaque sources are black-listed.
3536     case UO_Deref:
3537     case UO_AddrOf: // should be impossible
3538       return IntRange::forValueOfType(C, E->getType());
3539 
3540     default:
3541       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3542     }
3543   }
3544 
3545   if (dyn_cast<OffsetOfExpr>(E)) {
3546     IntRange::forValueOfType(C, E->getType());
3547   }
3548 
3549   if (FieldDecl *BitField = E->getBitField())
3550     return IntRange(BitField->getBitWidthValue(C),
3551                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
3552 
3553   return IntRange::forValueOfType(C, E->getType());
3554 }
3555 
3556 static IntRange GetExprRange(ASTContext &C, Expr *E) {
3557   return GetExprRange(C, E, C.getIntWidth(E->getType()));
3558 }
3559 
3560 /// Checks whether the given value, which currently has the given
3561 /// source semantics, has the same value when coerced through the
3562 /// target semantics.
3563 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
3564                                  const llvm::fltSemantics &Src,
3565                                  const llvm::fltSemantics &Tgt) {
3566   llvm::APFloat truncated = value;
3567 
3568   bool ignored;
3569   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3570   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3571 
3572   return truncated.bitwiseIsEqual(value);
3573 }
3574 
3575 /// Checks whether the given value, which currently has the given
3576 /// source semantics, has the same value when coerced through the
3577 /// target semantics.
3578 ///
3579 /// The value might be a vector of floats (or a complex number).
3580 static bool IsSameFloatAfterCast(const APValue &value,
3581                                  const llvm::fltSemantics &Src,
3582                                  const llvm::fltSemantics &Tgt) {
3583   if (value.isFloat())
3584     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3585 
3586   if (value.isVector()) {
3587     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3588       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3589         return false;
3590     return true;
3591   }
3592 
3593   assert(value.isComplexFloat());
3594   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3595           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3596 }
3597 
3598 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
3599 
3600 static bool IsZero(Sema &S, Expr *E) {
3601   // Suppress cases where we are comparing against an enum constant.
3602   if (const DeclRefExpr *DR =
3603       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3604     if (isa<EnumConstantDecl>(DR->getDecl()))
3605       return false;
3606 
3607   // Suppress cases where the '0' value is expanded from a macro.
3608   if (E->getLocStart().isMacroID())
3609     return false;
3610 
3611   llvm::APSInt Value;
3612   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3613 }
3614 
3615 static bool HasEnumType(Expr *E) {
3616   // Strip off implicit integral promotions.
3617   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3618     if (ICE->getCastKind() != CK_IntegralCast &&
3619         ICE->getCastKind() != CK_NoOp)
3620       break;
3621     E = ICE->getSubExpr();
3622   }
3623 
3624   return E->getType()->isEnumeralType();
3625 }
3626 
3627 static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
3628   BinaryOperatorKind op = E->getOpcode();
3629   if (E->isValueDependent())
3630     return;
3631 
3632   if (op == BO_LT && IsZero(S, E->getRHS())) {
3633     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3634       << "< 0" << "false" << HasEnumType(E->getLHS())
3635       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3636   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
3637     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3638       << ">= 0" << "true" << HasEnumType(E->getLHS())
3639       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3640   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
3641     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3642       << "0 >" << "false" << HasEnumType(E->getRHS())
3643       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3644   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
3645     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3646       << "0 <=" << "true" << HasEnumType(E->getRHS())
3647       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3648   }
3649 }
3650 
3651 /// Analyze the operands of the given comparison.  Implements the
3652 /// fallback case from AnalyzeComparison.
3653 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
3654   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3655   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3656 }
3657 
3658 /// \brief Implements -Wsign-compare.
3659 ///
3660 /// \param E the binary operator to check for warnings
3661 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3662   // The type the comparison is being performed in.
3663   QualType T = E->getLHS()->getType();
3664   assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3665          && "comparison with mismatched types");
3666 
3667   // We don't do anything special if this isn't an unsigned integral
3668   // comparison:  we're only interested in integral comparisons, and
3669   // signed comparisons only happen in cases we don't care to warn about.
3670   //
3671   // We also don't care about value-dependent expressions or expressions
3672   // whose result is a constant.
3673   if (!T->hasUnsignedIntegerRepresentation()
3674       || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
3675     return AnalyzeImpConvsInComparison(S, E);
3676 
3677   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3678   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
3679 
3680   // Check to see if one of the (unmodified) operands is of different
3681   // signedness.
3682   Expr *signedOperand, *unsignedOperand;
3683   if (LHS->getType()->hasSignedIntegerRepresentation()) {
3684     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
3685            "unsigned comparison between two signed integer expressions?");
3686     signedOperand = LHS;
3687     unsignedOperand = RHS;
3688   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3689     signedOperand = RHS;
3690     unsignedOperand = LHS;
3691   } else {
3692     CheckTrivialUnsignedComparison(S, E);
3693     return AnalyzeImpConvsInComparison(S, E);
3694   }
3695 
3696   // Otherwise, calculate the effective range of the signed operand.
3697   IntRange signedRange = GetExprRange(S.Context, signedOperand);
3698 
3699   // Go ahead and analyze implicit conversions in the operands.  Note
3700   // that we skip the implicit conversions on both sides.
3701   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3702   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
3703 
3704   // If the signed range is non-negative, -Wsign-compare won't fire,
3705   // but we should still check for comparisons which are always true
3706   // or false.
3707   if (signedRange.NonNegative)
3708     return CheckTrivialUnsignedComparison(S, E);
3709 
3710   // For (in)equality comparisons, if the unsigned operand is a
3711   // constant which cannot collide with a overflowed signed operand,
3712   // then reinterpreting the signed operand as unsigned will not
3713   // change the result of the comparison.
3714   if (E->isEqualityOp()) {
3715     unsigned comparisonWidth = S.Context.getIntWidth(T);
3716     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
3717 
3718     // We should never be unable to prove that the unsigned operand is
3719     // non-negative.
3720     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3721 
3722     if (unsignedRange.Width < comparisonWidth)
3723       return;
3724   }
3725 
3726   S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
3727     << LHS->getType() << RHS->getType()
3728     << LHS->getSourceRange() << RHS->getSourceRange();
3729 }
3730 
3731 /// Analyzes an attempt to assign the given value to a bitfield.
3732 ///
3733 /// Returns true if there was something fishy about the attempt.
3734 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3735                                       SourceLocation InitLoc) {
3736   assert(Bitfield->isBitField());
3737   if (Bitfield->isInvalidDecl())
3738     return false;
3739 
3740   // White-list bool bitfields.
3741   if (Bitfield->getType()->isBooleanType())
3742     return false;
3743 
3744   // Ignore value- or type-dependent expressions.
3745   if (Bitfield->getBitWidth()->isValueDependent() ||
3746       Bitfield->getBitWidth()->isTypeDependent() ||
3747       Init->isValueDependent() ||
3748       Init->isTypeDependent())
3749     return false;
3750 
3751   Expr *OriginalInit = Init->IgnoreParenImpCasts();
3752 
3753   llvm::APSInt Value;
3754   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
3755     return false;
3756 
3757   unsigned OriginalWidth = Value.getBitWidth();
3758   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
3759 
3760   if (OriginalWidth <= FieldWidth)
3761     return false;
3762 
3763   // Compute the value which the bitfield will contain.
3764   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
3765   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
3766 
3767   // Check whether the stored value is equal to the original value.
3768   TruncatedValue = TruncatedValue.extend(OriginalWidth);
3769   if (Value == TruncatedValue)
3770     return false;
3771 
3772   // Special-case bitfields of width 1: booleans are naturally 0/1, and
3773   // therefore don't strictly fit into a signed bitfield of width 1.
3774   if (FieldWidth == 1 && Value == 1)
3775     return false;
3776 
3777   std::string PrettyValue = Value.toString(10);
3778   std::string PrettyTrunc = TruncatedValue.toString(10);
3779 
3780   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3781     << PrettyValue << PrettyTrunc << OriginalInit->getType()
3782     << Init->getSourceRange();
3783 
3784   return true;
3785 }
3786 
3787 /// Analyze the given simple or compound assignment for warning-worthy
3788 /// operations.
3789 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3790   // Just recurse on the LHS.
3791   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3792 
3793   // We want to recurse on the RHS as normal unless we're assigning to
3794   // a bitfield.
3795   if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
3796     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3797                                   E->getOperatorLoc())) {
3798       // Recurse, ignoring any implicit conversions on the RHS.
3799       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3800                                         E->getOperatorLoc());
3801     }
3802   }
3803 
3804   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3805 }
3806 
3807 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3808 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3809                             SourceLocation CContext, unsigned diag,
3810                             bool pruneControlFlow = false) {
3811   if (pruneControlFlow) {
3812     S.DiagRuntimeBehavior(E->getExprLoc(), E,
3813                           S.PDiag(diag)
3814                             << SourceType << T << E->getSourceRange()
3815                             << SourceRange(CContext));
3816     return;
3817   }
3818   S.Diag(E->getExprLoc(), diag)
3819     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3820 }
3821 
3822 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3823 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
3824                             SourceLocation CContext, unsigned diag,
3825                             bool pruneControlFlow = false) {
3826   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
3827 }
3828 
3829 /// Diagnose an implicit cast from a literal expression. Does not warn when the
3830 /// cast wouldn't lose information.
3831 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3832                                     SourceLocation CContext) {
3833   // Try to convert the literal exactly to an integer. If we can, don't warn.
3834   bool isExact = false;
3835   const llvm::APFloat &Value = FL->getValue();
3836   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3837                             T->hasUnsignedIntegerRepresentation());
3838   if (Value.convertToInteger(IntegerValue,
3839                              llvm::APFloat::rmTowardZero, &isExact)
3840       == llvm::APFloat::opOK && isExact)
3841     return;
3842 
3843   S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3844     << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
3845 }
3846 
3847 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3848   if (!Range.Width) return "0";
3849 
3850   llvm::APSInt ValueInRange = Value;
3851   ValueInRange.setIsSigned(!Range.NonNegative);
3852   ValueInRange = ValueInRange.trunc(Range.Width);
3853   return ValueInRange.toString(10);
3854 }
3855 
3856 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
3857                              SourceLocation CC, bool *ICContext = 0) {
3858   if (E->isTypeDependent() || E->isValueDependent()) return;
3859 
3860   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3861   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3862   if (Source == Target) return;
3863   if (Target->isDependentType()) return;
3864 
3865   // If the conversion context location is invalid don't complain. We also
3866   // don't want to emit a warning if the issue occurs from the expansion of
3867   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3868   // delay this check as long as possible. Once we detect we are in that
3869   // scenario, we just return.
3870   if (CC.isInvalid())
3871     return;
3872 
3873   // Diagnose implicit casts to bool.
3874   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3875     if (isa<StringLiteral>(E))
3876       // Warn on string literal to bool.  Checks for string literals in logical
3877       // expressions, for instances, assert(0 && "error here"), is prevented
3878       // by a check in AnalyzeImplicitConversions().
3879       return DiagnoseImpCast(S, E, T, CC,
3880                              diag::warn_impcast_string_literal_to_bool);
3881     if (Source->isFunctionType()) {
3882       // Warn on function to bool. Checks free functions and static member
3883       // functions. Weakly imported functions are excluded from the check,
3884       // since it's common to test their value to check whether the linker
3885       // found a definition for them.
3886       ValueDecl *D = 0;
3887       if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3888         D = R->getDecl();
3889       } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3890         D = M->getMemberDecl();
3891       }
3892 
3893       if (D && !D->isWeak()) {
3894         if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3895           S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3896             << F << E->getSourceRange() << SourceRange(CC);
3897           S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3898             << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3899           QualType ReturnType;
3900           UnresolvedSet<4> NonTemplateOverloads;
3901           S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3902           if (!ReturnType.isNull()
3903               && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3904             S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3905               << FixItHint::CreateInsertion(
3906                  S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
3907           return;
3908         }
3909       }
3910     }
3911     return; // Other casts to bool are not checked.
3912   }
3913 
3914   // Strip vector types.
3915   if (isa<VectorType>(Source)) {
3916     if (!isa<VectorType>(Target)) {
3917       if (S.SourceMgr.isInSystemMacro(CC))
3918         return;
3919       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
3920     }
3921 
3922     // If the vector cast is cast between two vectors of the same size, it is
3923     // a bitcast, not a conversion.
3924     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3925       return;
3926 
3927     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3928     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3929   }
3930 
3931   // Strip complex types.
3932   if (isa<ComplexType>(Source)) {
3933     if (!isa<ComplexType>(Target)) {
3934       if (S.SourceMgr.isInSystemMacro(CC))
3935         return;
3936 
3937       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
3938     }
3939 
3940     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3941     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3942   }
3943 
3944   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3945   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3946 
3947   // If the source is floating point...
3948   if (SourceBT && SourceBT->isFloatingPoint()) {
3949     // ...and the target is floating point...
3950     if (TargetBT && TargetBT->isFloatingPoint()) {
3951       // ...then warn if we're dropping FP rank.
3952 
3953       // Builtin FP kinds are ordered by increasing FP rank.
3954       if (SourceBT->getKind() > TargetBT->getKind()) {
3955         // Don't warn about float constants that are precisely
3956         // representable in the target type.
3957         Expr::EvalResult result;
3958         if (E->EvaluateAsRValue(result, S.Context)) {
3959           // Value might be a float, a float vector, or a float complex.
3960           if (IsSameFloatAfterCast(result.Val,
3961                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3962                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
3963             return;
3964         }
3965 
3966         if (S.SourceMgr.isInSystemMacro(CC))
3967           return;
3968 
3969         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
3970       }
3971       return;
3972     }
3973 
3974     // If the target is integral, always warn.
3975     if ((TargetBT && TargetBT->isInteger())) {
3976       if (S.SourceMgr.isInSystemMacro(CC))
3977         return;
3978 
3979       Expr *InnerE = E->IgnoreParenImpCasts();
3980       // We also want to warn on, e.g., "int i = -1.234"
3981       if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3982         if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3983           InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3984 
3985       if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3986         DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
3987       } else {
3988         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3989       }
3990     }
3991 
3992     return;
3993   }
3994 
3995   if (!Source->isIntegerType() || !Target->isIntegerType())
3996     return;
3997 
3998   if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3999            == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
4000     S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
4001         << E->getSourceRange() << clang::SourceRange(CC);
4002     return;
4003   }
4004 
4005   IntRange SourceRange = GetExprRange(S.Context, E);
4006   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
4007 
4008   if (SourceRange.Width > TargetRange.Width) {
4009     // If the source is a constant, use a default-on diagnostic.
4010     // TODO: this should happen for bitfield stores, too.
4011     llvm::APSInt Value(32);
4012     if (E->isIntegerConstantExpr(Value, S.Context)) {
4013       if (S.SourceMgr.isInSystemMacro(CC))
4014         return;
4015 
4016       std::string PrettySourceValue = Value.toString(10);
4017       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4018 
4019       S.DiagRuntimeBehavior(E->getExprLoc(), E,
4020         S.PDiag(diag::warn_impcast_integer_precision_constant)
4021             << PrettySourceValue << PrettyTargetValue
4022             << E->getType() << T << E->getSourceRange()
4023             << clang::SourceRange(CC));
4024       return;
4025     }
4026 
4027     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
4028     if (S.SourceMgr.isInSystemMacro(CC))
4029       return;
4030 
4031     if (SourceRange.Width == 64 && TargetRange.Width == 32)
4032       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4033                              /* pruneControlFlow */ true);
4034     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
4035   }
4036 
4037   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4038       (!TargetRange.NonNegative && SourceRange.NonNegative &&
4039        SourceRange.Width == TargetRange.Width)) {
4040 
4041     if (S.SourceMgr.isInSystemMacro(CC))
4042       return;
4043 
4044     unsigned DiagID = diag::warn_impcast_integer_sign;
4045 
4046     // Traditionally, gcc has warned about this under -Wsign-compare.
4047     // We also want to warn about it in -Wconversion.
4048     // So if -Wconversion is off, use a completely identical diagnostic
4049     // in the sign-compare group.
4050     // The conditional-checking code will
4051     if (ICContext) {
4052       DiagID = diag::warn_impcast_integer_sign_conditional;
4053       *ICContext = true;
4054     }
4055 
4056     return DiagnoseImpCast(S, E, T, CC, DiagID);
4057   }
4058 
4059   // Diagnose conversions between different enumeration types.
4060   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4061   // type, to give us better diagnostics.
4062   QualType SourceType = E->getType();
4063   if (!S.getLangOptions().CPlusPlus) {
4064     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4065       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4066         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4067         SourceType = S.Context.getTypeDeclType(Enum);
4068         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4069       }
4070   }
4071 
4072   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4073     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4074       if ((SourceEnum->getDecl()->getIdentifier() ||
4075            SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
4076           (TargetEnum->getDecl()->getIdentifier() ||
4077            TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
4078           SourceEnum != TargetEnum) {
4079         if (S.SourceMgr.isInSystemMacro(CC))
4080           return;
4081 
4082         return DiagnoseImpCast(S, E, SourceType, T, CC,
4083                                diag::warn_impcast_different_enum_types);
4084       }
4085 
4086   return;
4087 }
4088 
4089 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
4090 
4091 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
4092                              SourceLocation CC, bool &ICContext) {
4093   E = E->IgnoreParenImpCasts();
4094 
4095   if (isa<ConditionalOperator>(E))
4096     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
4097 
4098   AnalyzeImplicitConversions(S, E, CC);
4099   if (E->getType() != T)
4100     return CheckImplicitConversion(S, E, T, CC, &ICContext);
4101   return;
4102 }
4103 
4104 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
4105   SourceLocation CC = E->getQuestionLoc();
4106 
4107   AnalyzeImplicitConversions(S, E->getCond(), CC);
4108 
4109   bool Suspicious = false;
4110   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4111   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
4112 
4113   // If -Wconversion would have warned about either of the candidates
4114   // for a signedness conversion to the context type...
4115   if (!Suspicious) return;
4116 
4117   // ...but it's currently ignored...
4118   if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4119                                  CC))
4120     return;
4121 
4122   // ...then check whether it would have warned about either of the
4123   // candidates for a signedness conversion to the condition type.
4124   if (E->getType() == T) return;
4125 
4126   Suspicious = false;
4127   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4128                           E->getType(), CC, &Suspicious);
4129   if (!Suspicious)
4130     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
4131                             E->getType(), CC, &Suspicious);
4132 }
4133 
4134 /// AnalyzeImplicitConversions - Find and report any interesting
4135 /// implicit conversions in the given expression.  There are a couple
4136 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
4137 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
4138   QualType T = OrigE->getType();
4139   Expr *E = OrigE->IgnoreParenImpCasts();
4140 
4141   if (E->isTypeDependent() || E->isValueDependent())
4142     return;
4143 
4144   // For conditional operators, we analyze the arguments as if they
4145   // were being fed directly into the output.
4146   if (isa<ConditionalOperator>(E)) {
4147     ConditionalOperator *CO = cast<ConditionalOperator>(E);
4148     CheckConditionalOperator(S, CO, T);
4149     return;
4150   }
4151 
4152   // Go ahead and check any implicit conversions we might have skipped.
4153   // The non-canonical typecheck is just an optimization;
4154   // CheckImplicitConversion will filter out dead implicit conversions.
4155   if (E->getType() != T)
4156     CheckImplicitConversion(S, E, T, CC);
4157 
4158   // Now continue drilling into this expression.
4159 
4160   // Skip past explicit casts.
4161   if (isa<ExplicitCastExpr>(E)) {
4162     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
4163     return AnalyzeImplicitConversions(S, E, CC);
4164   }
4165 
4166   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4167     // Do a somewhat different check with comparison operators.
4168     if (BO->isComparisonOp())
4169       return AnalyzeComparison(S, BO);
4170 
4171     // And with simple assignments.
4172     if (BO->getOpcode() == BO_Assign)
4173       return AnalyzeAssignment(S, BO);
4174   }
4175 
4176   // These break the otherwise-useful invariant below.  Fortunately,
4177   // we don't really need to recurse into them, because any internal
4178   // expressions should have been analyzed already when they were
4179   // built into statements.
4180   if (isa<StmtExpr>(E)) return;
4181 
4182   // Don't descend into unevaluated contexts.
4183   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
4184 
4185   // Now just recurse over the expression's children.
4186   CC = E->getExprLoc();
4187   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4188   bool IsLogicalOperator = BO && BO->isLogicalOp();
4189   for (Stmt::child_range I = E->children(); I; ++I) {
4190     Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
4191     if (!ChildExpr)
4192       continue;
4193 
4194     if (IsLogicalOperator &&
4195         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4196       // Ignore checking string literals that are in logical operators.
4197       continue;
4198     AnalyzeImplicitConversions(S, ChildExpr, CC);
4199   }
4200 }
4201 
4202 } // end anonymous namespace
4203 
4204 /// Diagnoses "dangerous" implicit conversions within the given
4205 /// expression (which is a full expression).  Implements -Wconversion
4206 /// and -Wsign-compare.
4207 ///
4208 /// \param CC the "context" location of the implicit conversion, i.e.
4209 ///   the most location of the syntactic entity requiring the implicit
4210 ///   conversion
4211 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
4212   // Don't diagnose in unevaluated contexts.
4213   if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4214     return;
4215 
4216   // Don't diagnose for value- or type-dependent expressions.
4217   if (E->isTypeDependent() || E->isValueDependent())
4218     return;
4219 
4220   // Check for array bounds violations in cases where the check isn't triggered
4221   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4222   // ArraySubscriptExpr is on the RHS of a variable initialization.
4223   CheckArrayAccess(E);
4224 
4225   // This is not the right CC for (e.g.) a variable initialization.
4226   AnalyzeImplicitConversions(*this, E, CC);
4227 }
4228 
4229 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4230                                        FieldDecl *BitField,
4231                                        Expr *Init) {
4232   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4233 }
4234 
4235 /// CheckParmsForFunctionDef - Check that the parameters of the given
4236 /// function are appropriate for the definition of a function. This
4237 /// takes care of any checks that cannot be performed on the
4238 /// declaration itself, e.g., that the types of each of the function
4239 /// parameters are complete.
4240 bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4241                                     bool CheckParameterNames) {
4242   bool HasInvalidParm = false;
4243   for (; P != PEnd; ++P) {
4244     ParmVarDecl *Param = *P;
4245 
4246     // C99 6.7.5.3p4: the parameters in a parameter type list in a
4247     // function declarator that is part of a function definition of
4248     // that function shall not have incomplete type.
4249     //
4250     // This is also C++ [dcl.fct]p6.
4251     if (!Param->isInvalidDecl() &&
4252         RequireCompleteType(Param->getLocation(), Param->getType(),
4253                                diag::err_typecheck_decl_incomplete_type)) {
4254       Param->setInvalidDecl();
4255       HasInvalidParm = true;
4256     }
4257 
4258     // C99 6.9.1p5: If the declarator includes a parameter type list, the
4259     // declaration of each parameter shall include an identifier.
4260     if (CheckParameterNames &&
4261         Param->getIdentifier() == 0 &&
4262         !Param->isImplicit() &&
4263         !getLangOptions().CPlusPlus)
4264       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
4265 
4266     // C99 6.7.5.3p12:
4267     //   If the function declarator is not part of a definition of that
4268     //   function, parameters may have incomplete type and may use the [*]
4269     //   notation in their sequences of declarator specifiers to specify
4270     //   variable length array types.
4271     QualType PType = Param->getOriginalType();
4272     if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4273       if (AT->getSizeModifier() == ArrayType::Star) {
4274         // FIXME: This diagnosic should point the the '[*]' if source-location
4275         // information is added for it.
4276         Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4277       }
4278     }
4279   }
4280 
4281   return HasInvalidParm;
4282 }
4283 
4284 /// CheckCastAlign - Implements -Wcast-align, which warns when a
4285 /// pointer cast increases the alignment requirements.
4286 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4287   // This is actually a lot of work to potentially be doing on every
4288   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
4289   if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4290                                           TRange.getBegin())
4291         == DiagnosticsEngine::Ignored)
4292     return;
4293 
4294   // Ignore dependent types.
4295   if (T->isDependentType() || Op->getType()->isDependentType())
4296     return;
4297 
4298   // Require that the destination be a pointer type.
4299   const PointerType *DestPtr = T->getAs<PointerType>();
4300   if (!DestPtr) return;
4301 
4302   // If the destination has alignment 1, we're done.
4303   QualType DestPointee = DestPtr->getPointeeType();
4304   if (DestPointee->isIncompleteType()) return;
4305   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4306   if (DestAlign.isOne()) return;
4307 
4308   // Require that the source be a pointer type.
4309   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4310   if (!SrcPtr) return;
4311   QualType SrcPointee = SrcPtr->getPointeeType();
4312 
4313   // Whitelist casts from cv void*.  We already implicitly
4314   // whitelisted casts to cv void*, since they have alignment 1.
4315   // Also whitelist casts involving incomplete types, which implicitly
4316   // includes 'void'.
4317   if (SrcPointee->isIncompleteType()) return;
4318 
4319   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4320   if (SrcAlign >= DestAlign) return;
4321 
4322   Diag(TRange.getBegin(), diag::warn_cast_align)
4323     << Op->getType() << T
4324     << static_cast<unsigned>(SrcAlign.getQuantity())
4325     << static_cast<unsigned>(DestAlign.getQuantity())
4326     << TRange << Op->getSourceRange();
4327 }
4328 
4329 static const Type* getElementType(const Expr *BaseExpr) {
4330   const Type* EltType = BaseExpr->getType().getTypePtr();
4331   if (EltType->isAnyPointerType())
4332     return EltType->getPointeeType().getTypePtr();
4333   else if (EltType->isArrayType())
4334     return EltType->getBaseElementTypeUnsafe();
4335   return EltType;
4336 }
4337 
4338 /// \brief Check whether this array fits the idiom of a size-one tail padded
4339 /// array member of a struct.
4340 ///
4341 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
4342 /// commonly used to emulate flexible arrays in C89 code.
4343 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4344                                     const NamedDecl *ND) {
4345   if (Size != 1 || !ND) return false;
4346 
4347   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4348   if (!FD) return false;
4349 
4350   // Don't consider sizes resulting from macro expansions or template argument
4351   // substitution to form C89 tail-padded arrays.
4352   ConstantArrayTypeLoc TL =
4353     cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4354   const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4355   if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4356     return false;
4357 
4358   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
4359   if (!RD) return false;
4360   if (RD->isUnion()) return false;
4361   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4362     if (!CRD->isStandardLayout()) return false;
4363   }
4364 
4365   // See if this is the last field decl in the record.
4366   const Decl *D = FD;
4367   while ((D = D->getNextDeclInContext()))
4368     if (isa<FieldDecl>(D))
4369       return false;
4370   return true;
4371 }
4372 
4373 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
4374                             const ArraySubscriptExpr *ASE,
4375                             bool AllowOnePastEnd, bool IndexNegated) {
4376   IndexExpr = IndexExpr->IgnoreParenCasts();
4377   if (IndexExpr->isValueDependent())
4378     return;
4379 
4380   const Type *EffectiveType = getElementType(BaseExpr);
4381   BaseExpr = BaseExpr->IgnoreParenCasts();
4382   const ConstantArrayType *ArrayTy =
4383     Context.getAsConstantArrayType(BaseExpr->getType());
4384   if (!ArrayTy)
4385     return;
4386 
4387   llvm::APSInt index;
4388   if (!IndexExpr->EvaluateAsInt(index, Context))
4389     return;
4390   if (IndexNegated)
4391     index = -index;
4392 
4393   const NamedDecl *ND = NULL;
4394   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4395     ND = dyn_cast<NamedDecl>(DRE->getDecl());
4396   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4397     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4398 
4399   if (index.isUnsigned() || !index.isNegative()) {
4400     llvm::APInt size = ArrayTy->getSize();
4401     if (!size.isStrictlyPositive())
4402       return;
4403 
4404     const Type* BaseType = getElementType(BaseExpr);
4405     if (BaseType != EffectiveType) {
4406       // Make sure we're comparing apples to apples when comparing index to size
4407       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4408       uint64_t array_typesize = Context.getTypeSize(BaseType);
4409       // Handle ptrarith_typesize being zero, such as when casting to void*
4410       if (!ptrarith_typesize) ptrarith_typesize = 1;
4411       if (ptrarith_typesize != array_typesize) {
4412         // There's a cast to a different size type involved
4413         uint64_t ratio = array_typesize / ptrarith_typesize;
4414         // TODO: Be smarter about handling cases where array_typesize is not a
4415         // multiple of ptrarith_typesize
4416         if (ptrarith_typesize * ratio == array_typesize)
4417           size *= llvm::APInt(size.getBitWidth(), ratio);
4418       }
4419     }
4420 
4421     if (size.getBitWidth() > index.getBitWidth())
4422       index = index.sext(size.getBitWidth());
4423     else if (size.getBitWidth() < index.getBitWidth())
4424       size = size.sext(index.getBitWidth());
4425 
4426     // For array subscripting the index must be less than size, but for pointer
4427     // arithmetic also allow the index (offset) to be equal to size since
4428     // computing the next address after the end of the array is legal and
4429     // commonly done e.g. in C++ iterators and range-based for loops.
4430     if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
4431       return;
4432 
4433     // Also don't warn for arrays of size 1 which are members of some
4434     // structure. These are often used to approximate flexible arrays in C89
4435     // code.
4436     if (IsTailPaddedMemberArray(*this, size, ND))
4437       return;
4438 
4439     // Suppress the warning if the subscript expression (as identified by the
4440     // ']' location) and the index expression are both from macro expansions
4441     // within a system header.
4442     if (ASE) {
4443       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4444           ASE->getRBracketLoc());
4445       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4446         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4447             IndexExpr->getLocStart());
4448         if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4449           return;
4450       }
4451     }
4452 
4453     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
4454     if (ASE)
4455       DiagID = diag::warn_array_index_exceeds_bounds;
4456 
4457     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4458                         PDiag(DiagID) << index.toString(10, true)
4459                           << size.toString(10, true)
4460                           << (unsigned)size.getLimitedValue(~0U)
4461                           << IndexExpr->getSourceRange());
4462   } else {
4463     unsigned DiagID = diag::warn_array_index_precedes_bounds;
4464     if (!ASE) {
4465       DiagID = diag::warn_ptr_arith_precedes_bounds;
4466       if (index.isNegative()) index = -index;
4467     }
4468 
4469     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4470                         PDiag(DiagID) << index.toString(10, true)
4471                           << IndexExpr->getSourceRange());
4472   }
4473 
4474   if (!ND) {
4475     // Try harder to find a NamedDecl to point at in the note.
4476     while (const ArraySubscriptExpr *ASE =
4477            dyn_cast<ArraySubscriptExpr>(BaseExpr))
4478       BaseExpr = ASE->getBase()->IgnoreParenCasts();
4479     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4480       ND = dyn_cast<NamedDecl>(DRE->getDecl());
4481     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4482       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4483   }
4484 
4485   if (ND)
4486     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4487                         PDiag(diag::note_array_index_out_of_bounds)
4488                           << ND->getDeclName());
4489 }
4490 
4491 void Sema::CheckArrayAccess(const Expr *expr) {
4492   int AllowOnePastEnd = 0;
4493   while (expr) {
4494     expr = expr->IgnoreParenImpCasts();
4495     switch (expr->getStmtClass()) {
4496       case Stmt::ArraySubscriptExprClass: {
4497         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
4498         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
4499                          AllowOnePastEnd > 0);
4500         return;
4501       }
4502       case Stmt::UnaryOperatorClass: {
4503         // Only unwrap the * and & unary operators
4504         const UnaryOperator *UO = cast<UnaryOperator>(expr);
4505         expr = UO->getSubExpr();
4506         switch (UO->getOpcode()) {
4507           case UO_AddrOf:
4508             AllowOnePastEnd++;
4509             break;
4510           case UO_Deref:
4511             AllowOnePastEnd--;
4512             break;
4513           default:
4514             return;
4515         }
4516         break;
4517       }
4518       case Stmt::ConditionalOperatorClass: {
4519         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4520         if (const Expr *lhs = cond->getLHS())
4521           CheckArrayAccess(lhs);
4522         if (const Expr *rhs = cond->getRHS())
4523           CheckArrayAccess(rhs);
4524         return;
4525       }
4526       default:
4527         return;
4528     }
4529   }
4530 }
4531 
4532 //===--- CHECK: Objective-C retain cycles ----------------------------------//
4533 
4534 namespace {
4535   struct RetainCycleOwner {
4536     RetainCycleOwner() : Variable(0), Indirect(false) {}
4537     VarDecl *Variable;
4538     SourceRange Range;
4539     SourceLocation Loc;
4540     bool Indirect;
4541 
4542     void setLocsFrom(Expr *e) {
4543       Loc = e->getExprLoc();
4544       Range = e->getSourceRange();
4545     }
4546   };
4547 }
4548 
4549 /// Consider whether capturing the given variable can possibly lead to
4550 /// a retain cycle.
4551 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4552   // In ARC, it's captured strongly iff the variable has __strong
4553   // lifetime.  In MRR, it's captured strongly if the variable is
4554   // __block and has an appropriate type.
4555   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4556     return false;
4557 
4558   owner.Variable = var;
4559   owner.setLocsFrom(ref);
4560   return true;
4561 }
4562 
4563 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
4564   while (true) {
4565     e = e->IgnoreParens();
4566     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4567       switch (cast->getCastKind()) {
4568       case CK_BitCast:
4569       case CK_LValueBitCast:
4570       case CK_LValueToRValue:
4571       case CK_ARCReclaimReturnedObject:
4572         e = cast->getSubExpr();
4573         continue;
4574 
4575       default:
4576         return false;
4577       }
4578     }
4579 
4580     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4581       ObjCIvarDecl *ivar = ref->getDecl();
4582       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4583         return false;
4584 
4585       // Try to find a retain cycle in the base.
4586       if (!findRetainCycleOwner(S, ref->getBase(), owner))
4587         return false;
4588 
4589       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4590       owner.Indirect = true;
4591       return true;
4592     }
4593 
4594     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4595       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4596       if (!var) return false;
4597       return considerVariable(var, ref, owner);
4598     }
4599 
4600     if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4601       owner.Variable = ref->getDecl();
4602       owner.setLocsFrom(ref);
4603       return true;
4604     }
4605 
4606     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4607       if (member->isArrow()) return false;
4608 
4609       // Don't count this as an indirect ownership.
4610       e = member->getBase();
4611       continue;
4612     }
4613 
4614     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4615       // Only pay attention to pseudo-objects on property references.
4616       ObjCPropertyRefExpr *pre
4617         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4618                                               ->IgnoreParens());
4619       if (!pre) return false;
4620       if (pre->isImplicitProperty()) return false;
4621       ObjCPropertyDecl *property = pre->getExplicitProperty();
4622       if (!property->isRetaining() &&
4623           !(property->getPropertyIvarDecl() &&
4624             property->getPropertyIvarDecl()->getType()
4625               .getObjCLifetime() == Qualifiers::OCL_Strong))
4626           return false;
4627 
4628       owner.Indirect = true;
4629       if (pre->isSuperReceiver()) {
4630         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4631         if (!owner.Variable)
4632           return false;
4633         owner.Loc = pre->getLocation();
4634         owner.Range = pre->getSourceRange();
4635         return true;
4636       }
4637       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4638                               ->getSourceExpr());
4639       continue;
4640     }
4641 
4642     // Array ivars?
4643 
4644     return false;
4645   }
4646 }
4647 
4648 namespace {
4649   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4650     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4651       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4652         Variable(variable), Capturer(0) {}
4653 
4654     VarDecl *Variable;
4655     Expr *Capturer;
4656 
4657     void VisitDeclRefExpr(DeclRefExpr *ref) {
4658       if (ref->getDecl() == Variable && !Capturer)
4659         Capturer = ref;
4660     }
4661 
4662     void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4663       if (ref->getDecl() == Variable && !Capturer)
4664         Capturer = ref;
4665     }
4666 
4667     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4668       if (Capturer) return;
4669       Visit(ref->getBase());
4670       if (Capturer && ref->isFreeIvar())
4671         Capturer = ref;
4672     }
4673 
4674     void VisitBlockExpr(BlockExpr *block) {
4675       // Look inside nested blocks
4676       if (block->getBlockDecl()->capturesVariable(Variable))
4677         Visit(block->getBlockDecl()->getBody());
4678     }
4679   };
4680 }
4681 
4682 /// Check whether the given argument is a block which captures a
4683 /// variable.
4684 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4685   assert(owner.Variable && owner.Loc.isValid());
4686 
4687   e = e->IgnoreParenCasts();
4688   BlockExpr *block = dyn_cast<BlockExpr>(e);
4689   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4690     return 0;
4691 
4692   FindCaptureVisitor visitor(S.Context, owner.Variable);
4693   visitor.Visit(block->getBlockDecl()->getBody());
4694   return visitor.Capturer;
4695 }
4696 
4697 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4698                                 RetainCycleOwner &owner) {
4699   assert(capturer);
4700   assert(owner.Variable && owner.Loc.isValid());
4701 
4702   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4703     << owner.Variable << capturer->getSourceRange();
4704   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4705     << owner.Indirect << owner.Range;
4706 }
4707 
4708 /// Check for a keyword selector that starts with the word 'add' or
4709 /// 'set'.
4710 static bool isSetterLikeSelector(Selector sel) {
4711   if (sel.isUnarySelector()) return false;
4712 
4713   StringRef str = sel.getNameForSlot(0);
4714   while (!str.empty() && str.front() == '_') str = str.substr(1);
4715   if (str.startswith("set"))
4716     str = str.substr(3);
4717   else if (str.startswith("add")) {
4718     // Specially whitelist 'addOperationWithBlock:'.
4719     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4720       return false;
4721     str = str.substr(3);
4722   }
4723   else
4724     return false;
4725 
4726   if (str.empty()) return true;
4727   return !islower(str.front());
4728 }
4729 
4730 /// Check a message send to see if it's likely to cause a retain cycle.
4731 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4732   // Only check instance methods whose selector looks like a setter.
4733   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4734     return;
4735 
4736   // Try to find a variable that the receiver is strongly owned by.
4737   RetainCycleOwner owner;
4738   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4739     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
4740       return;
4741   } else {
4742     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4743     owner.Variable = getCurMethodDecl()->getSelfDecl();
4744     owner.Loc = msg->getSuperLoc();
4745     owner.Range = msg->getSuperLoc();
4746   }
4747 
4748   // Check whether the receiver is captured by any of the arguments.
4749   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4750     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4751       return diagnoseRetainCycle(*this, capturer, owner);
4752 }
4753 
4754 /// Check a property assign to see if it's likely to cause a retain cycle.
4755 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4756   RetainCycleOwner owner;
4757   if (!findRetainCycleOwner(*this, receiver, owner))
4758     return;
4759 
4760   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4761     diagnoseRetainCycle(*this, capturer, owner);
4762 }
4763 
4764 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
4765                               QualType LHS, Expr *RHS) {
4766   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4767   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
4768     return false;
4769   // strip off any implicit cast added to get to the one arc-specific
4770   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4771     if (cast->getCastKind() == CK_ARCConsumeObject) {
4772       Diag(Loc, diag::warn_arc_retained_assign)
4773         << (LT == Qualifiers::OCL_ExplicitNone)
4774         << RHS->getSourceRange();
4775       return true;
4776     }
4777     RHS = cast->getSubExpr();
4778   }
4779   return false;
4780 }
4781 
4782 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4783                               Expr *LHS, Expr *RHS) {
4784   QualType LHSType;
4785   // PropertyRef on LHS type need be directly obtained from
4786   // its declaration as it has a PsuedoType.
4787   ObjCPropertyRefExpr *PRE
4788     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
4789   if (PRE && !PRE->isImplicitProperty()) {
4790     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4791     if (PD)
4792       LHSType = PD->getType();
4793   }
4794 
4795   if (LHSType.isNull())
4796     LHSType = LHS->getType();
4797   if (checkUnsafeAssigns(Loc, LHSType, RHS))
4798     return;
4799   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4800   // FIXME. Check for other life times.
4801   if (LT != Qualifiers::OCL_None)
4802     return;
4803 
4804   if (PRE) {
4805     if (PRE->isImplicitProperty())
4806       return;
4807     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4808     if (!PD)
4809       return;
4810 
4811     unsigned Attributes = PD->getPropertyAttributes();
4812     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
4813       // when 'assign' attribute was not explicitly specified
4814       // by user, ignore it and rely on property type itself
4815       // for lifetime info.
4816       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
4817       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
4818           LHSType->isObjCRetainableType())
4819         return;
4820 
4821       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4822         if (cast->getCastKind() == CK_ARCConsumeObject) {
4823           Diag(Loc, diag::warn_arc_retained_property_assign)
4824           << RHS->getSourceRange();
4825           return;
4826         }
4827         RHS = cast->getSubExpr();
4828       }
4829     }
4830   }
4831 }
4832 
4833 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
4834 
4835 namespace {
4836 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
4837                                  SourceLocation StmtLoc,
4838                                  const NullStmt *Body) {
4839   // Do not warn if the body is a macro that expands to nothing, e.g:
4840   //
4841   // #define CALL(x)
4842   // if (condition)
4843   //   CALL(0);
4844   //
4845   if (Body->hasLeadingEmptyMacro())
4846     return false;
4847 
4848   // Get line numbers of statement and body.
4849   bool StmtLineInvalid;
4850   unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
4851                                                       &StmtLineInvalid);
4852   if (StmtLineInvalid)
4853     return false;
4854 
4855   bool BodyLineInvalid;
4856   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
4857                                                       &BodyLineInvalid);
4858   if (BodyLineInvalid)
4859     return false;
4860 
4861   // Warn if null statement and body are on the same line.
4862   if (StmtLine != BodyLine)
4863     return false;
4864 
4865   return true;
4866 }
4867 } // Unnamed namespace
4868 
4869 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4870                                  const Stmt *Body,
4871                                  unsigned DiagID) {
4872   // Since this is a syntactic check, don't emit diagnostic for template
4873   // instantiations, this just adds noise.
4874   if (CurrentInstantiationScope)
4875     return;
4876 
4877   // The body should be a null statement.
4878   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
4879   if (!NBody)
4880     return;
4881 
4882   // Do the usual checks.
4883   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
4884     return;
4885 
4886   Diag(NBody->getSemiLoc(), DiagID);
4887   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
4888 }
4889 
4890 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
4891                                  const Stmt *PossibleBody) {
4892   assert(!CurrentInstantiationScope); // Ensured by caller
4893 
4894   SourceLocation StmtLoc;
4895   const Stmt *Body;
4896   unsigned DiagID;
4897   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
4898     StmtLoc = FS->getRParenLoc();
4899     Body = FS->getBody();
4900     DiagID = diag::warn_empty_for_body;
4901   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
4902     StmtLoc = WS->getCond()->getSourceRange().getEnd();
4903     Body = WS->getBody();
4904     DiagID = diag::warn_empty_while_body;
4905   } else
4906     return; // Neither `for' nor `while'.
4907 
4908   // The body should be a null statement.
4909   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
4910   if (!NBody)
4911     return;
4912 
4913   // Skip expensive checks if diagnostic is disabled.
4914   if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
4915           DiagnosticsEngine::Ignored)
4916     return;
4917 
4918   // Do the usual checks.
4919   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
4920     return;
4921 
4922   // `for(...);' and `while(...);' are popular idioms, so in order to keep
4923   // noise level low, emit diagnostics only if for/while is followed by a
4924   // CompoundStmt, e.g.:
4925   //    for (int i = 0; i < n; i++);
4926   //    {
4927   //      a(i);
4928   //    }
4929   // or if for/while is followed by a statement with more indentation
4930   // than for/while itself:
4931   //    for (int i = 0; i < n; i++);
4932   //      a(i);
4933   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
4934   if (!ProbableTypo) {
4935     bool BodyColInvalid;
4936     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
4937                              PossibleBody->getLocStart(),
4938                              &BodyColInvalid);
4939     if (BodyColInvalid)
4940       return;
4941 
4942     bool StmtColInvalid;
4943     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
4944                              S->getLocStart(),
4945                              &StmtColInvalid);
4946     if (StmtColInvalid)
4947       return;
4948 
4949     if (BodyCol > StmtCol)
4950       ProbableTypo = true;
4951   }
4952 
4953   if (ProbableTypo) {
4954     Diag(NBody->getSemiLoc(), DiagID);
4955     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
4956   }
4957 }
4958 
4959