blob: 16c058c3e6ab235431927b4219207b2192de6676 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
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// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
76 unsigned RewriteFailedDiag;
77 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
81
82 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
85 unsigned TryFinallyContainsReturnDiag;
86 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
104
105 /* Misc. containers needed for meta-data rewrite. */
106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
111 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
112 SmallVector<Stmt *, 32> Stmts;
113 SmallVector<int, 8> ObjCBcLabelNo;
114 // Remember all the @protocol(<expr>) expressions.
115 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
116
117 llvm::DenseSet<uint64_t> CopyDestroyCache;
118
119 // Block expressions.
120 SmallVector<BlockExpr *, 32> Blocks;
121 SmallVector<int, 32> InnerDeclRefsCount;
122 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
123
124 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
125
126 // Block related declarations.
127 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
129 SmallVector<ValueDecl *, 8> BlockByRefDecls;
130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
131 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
132 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
133 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
134
135 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
136
137 // This maps an original source AST to it's rewritten form. This allows
138 // us to avoid rewriting the same node twice (which is very uncommon).
139 // This is needed to support some of the exotic property rewriting.
140 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
141
142 // Needed for header files being rewritten
143 bool IsHeader;
144 bool SilenceRewriteMacroWarning;
145 bool objc_impl_method;
146
147 bool DisableReplaceStmt;
148 class DisableReplaceStmtScope {
149 RewriteModernObjC &R;
150 bool SavedValue;
151
152 public:
153 DisableReplaceStmtScope(RewriteModernObjC &R)
154 : R(R), SavedValue(R.DisableReplaceStmt) {
155 R.DisableReplaceStmt = true;
156 }
157 ~DisableReplaceStmtScope() {
158 R.DisableReplaceStmt = SavedValue;
159 }
160 };
161 void InitializeCommon(ASTContext &context);
162
163 public:
164
165 // Top Level Driver code.
166 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
167 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
168 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
169 if (!Class->isThisDeclarationADefinition()) {
170 RewriteForwardClassDecl(D);
171 break;
172 }
173 }
174
175 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
176 if (!Proto->isThisDeclarationADefinition()) {
177 RewriteForwardProtocolDecl(D);
178 break;
179 }
180 }
181
182 HandleTopLevelSingleDecl(*I);
183 }
184 return true;
185 }
186 void HandleTopLevelSingleDecl(Decl *D);
187 void HandleDeclInMainFile(Decl *D);
188 RewriteModernObjC(std::string inFile, raw_ostream *OS,
189 DiagnosticsEngine &D, const LangOptions &LOpts,
190 bool silenceMacroWarn);
191
192 ~RewriteModernObjC() {}
193
194 virtual void HandleTranslationUnit(ASTContext &C);
195
196 void ReplaceStmt(Stmt *Old, Stmt *New) {
197 Stmt *ReplacingStmt = ReplacedNodes[Old];
198
199 if (ReplacingStmt)
200 return; // We can't rewrite the same node twice.
201
202 if (DisableReplaceStmt)
203 return;
204
205 // If replacement succeeded or warning disabled return with no warning.
206 if (!Rewrite.ReplaceStmt(Old, New)) {
207 ReplacedNodes[Old] = New;
208 return;
209 }
210 if (SilenceRewriteMacroWarning)
211 return;
212 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
213 << Old->getSourceRange();
214 }
215
216 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
217 if (DisableReplaceStmt)
218 return;
219
220 // Measure the old text.
221 int Size = Rewrite.getRangeSize(SrcRange);
222 if (Size == -1) {
223 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
224 << Old->getSourceRange();
225 return;
226 }
227 // Get the new text.
228 std::string SStr;
229 llvm::raw_string_ostream S(SStr);
230 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
231 const std::string &Str = S.str();
232
233 // If replacement succeeded or warning disabled return with no warning.
234 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
235 ReplacedNodes[Old] = New;
236 return;
237 }
238 if (SilenceRewriteMacroWarning)
239 return;
240 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
241 << Old->getSourceRange();
242 }
243
244 void InsertText(SourceLocation Loc, StringRef Str,
245 bool InsertAfter = true) {
246 // If insertion succeeded or warning disabled return with no warning.
247 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
248 SilenceRewriteMacroWarning)
249 return;
250
251 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
252 }
253
254 void ReplaceText(SourceLocation Start, unsigned OrigLength,
255 StringRef Str) {
256 // If removal succeeded or warning disabled return with no warning.
257 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
258 SilenceRewriteMacroWarning)
259 return;
260
261 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
262 }
263
264 // Syntactic Rewriting.
265 void RewriteRecordBody(RecordDecl *RD);
266 void RewriteInclude();
267 void RewriteForwardClassDecl(DeclGroupRef D);
268 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
269 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
270 const std::string &typedefString);
271 void RewriteImplementations();
272 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
273 ObjCImplementationDecl *IMD,
274 ObjCCategoryImplDecl *CID);
275 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
276 void RewriteImplementationDecl(Decl *Dcl);
277 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
278 ObjCMethodDecl *MDecl, std::string &ResultStr);
279 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
280 const FunctionType *&FPRetType);
281 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
282 ValueDecl *VD, bool def=false);
283 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
284 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
285 void RewriteForwardProtocolDecl(DeclGroupRef D);
286 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
287 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
288 void RewriteProperty(ObjCPropertyDecl *prop);
289 void RewriteFunctionDecl(FunctionDecl *FD);
290 void RewriteBlockPointerType(std::string& Str, QualType Type);
291 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
292 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
293 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
294 void RewriteTypeOfDecl(VarDecl *VD);
295 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
296
297 // Expression Rewriting.
298 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
299 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
300 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
301 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
302 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
303 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
304 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
305 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
306 void RewriteTryReturnStmts(Stmt *S);
307 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
308 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
309 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
310 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
311 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
312 SourceLocation OrigEnd);
313 Stmt *RewriteBreakStmt(BreakStmt *S);
314 Stmt *RewriteContinueStmt(ContinueStmt *S);
315 void RewriteCastExpr(CStyleCastExpr *CE);
316
317 // Block rewriting.
318 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
319
320 // Block specific rewrite rules.
321 void RewriteBlockPointerDecl(NamedDecl *VD);
322 void RewriteByRefVar(VarDecl *VD);
323 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
324 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
325 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
326
327 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
328 std::string &Result);
329
330 virtual void Initialize(ASTContext &context);
331
332 // Misc. AST transformation routines. Somtimes they end up calling
333 // rewriting routines on the new ASTs.
334 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
335 Expr **args, unsigned nargs,
336 SourceLocation StartLoc=SourceLocation(),
337 SourceLocation EndLoc=SourceLocation());
338
339 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
340 SourceLocation StartLoc=SourceLocation(),
341 SourceLocation EndLoc=SourceLocation());
342
343 void SynthCountByEnumWithState(std::string &buf);
344 void SynthMsgSendFunctionDecl();
345 void SynthMsgSendSuperFunctionDecl();
346 void SynthMsgSendStretFunctionDecl();
347 void SynthMsgSendFpretFunctionDecl();
348 void SynthMsgSendSuperStretFunctionDecl();
349 void SynthGetClassFunctionDecl();
350 void SynthGetMetaClassFunctionDecl();
351 void SynthGetSuperClassFunctionDecl();
352 void SynthSelGetUidFunctionDecl();
353 void SynthSuperContructorFunctionDecl();
354
355 // Rewriting metadata
356 template<typename MethodIterator>
357 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
358 MethodIterator MethodEnd,
359 bool IsInstanceMethod,
360 StringRef prefix,
361 StringRef ClassName,
362 std::string &Result);
363 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
364 StringRef prefix,
365 StringRef ClassName,
366 std::string &Result);
367 virtual void RewriteObjCProtocolListMetaData(
368 const ObjCList<ObjCProtocolDecl> &Prots,
369 StringRef prefix, StringRef ClassName, std::string &Result);
370 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
371 std::string &Result);
372 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
373 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
374 std::string &Result);
375
376 // Rewriting ivar
377 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
378 std::string &Result);
379 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
380
381
382 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
383 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
384 StringRef funcName, std::string Tag);
385 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
386 StringRef funcName, std::string Tag);
387 std::string SynthesizeBlockImpl(BlockExpr *CE,
388 std::string Tag, std::string Desc);
389 std::string SynthesizeBlockDescriptor(std::string DescTag,
390 std::string ImplTag,
391 int i, StringRef funcName,
392 unsigned hasCopy);
393 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
394 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
395 StringRef FunName);
396 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
397 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
398 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
399
400 // Misc. helper routines.
401 QualType getProtocolType();
402 void WarnAboutReturnGotoStmts(Stmt *S);
403 void HasReturnStmts(Stmt *S, bool &hasReturns);
404 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
405 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
406 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
407
408 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
409 void CollectBlockDeclRefInfo(BlockExpr *Exp);
410 void GetBlockDeclRefExprs(Stmt *S);
411 void GetInnerBlockDeclRefExprs(Stmt *S,
412 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
413 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
414
415 // We avoid calling Type::isBlockPointerType(), since it operates on the
416 // canonical type. We only care if the top-level type is a closure pointer.
417 bool isTopLevelBlockPointerType(QualType T) {
418 return isa<BlockPointerType>(T);
419 }
420
421 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
422 /// to a function pointer type and upon success, returns true; false
423 /// otherwise.
424 bool convertBlockPointerToFunctionPointer(QualType &T) {
425 if (isTopLevelBlockPointerType(T)) {
426 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
427 T = Context->getPointerType(BPT->getPointeeType());
428 return true;
429 }
430 return false;
431 }
432
433 bool needToScanForQualifiers(QualType T);
434 QualType getSuperStructType();
435 QualType getConstantStringStructType();
436 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
437 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
438
439 void convertToUnqualifiedObjCType(QualType &T) {
440 if (T->isObjCQualifiedIdType())
441 T = Context->getObjCIdType();
442 else if (T->isObjCQualifiedClassType())
443 T = Context->getObjCClassType();
444 else if (T->isObjCObjectPointerType() &&
445 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
446 if (const ObjCObjectPointerType * OBJPT =
447 T->getAsObjCInterfacePointerType()) {
448 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
449 T = QualType(IFaceT, 0);
450 T = Context->getPointerType(T);
451 }
452 }
453 }
454
455 // FIXME: This predicate seems like it would be useful to add to ASTContext.
456 bool isObjCType(QualType T) {
457 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
458 return false;
459
460 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
461
462 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
463 OCT == Context->getCanonicalType(Context->getObjCClassType()))
464 return true;
465
466 if (const PointerType *PT = OCT->getAs<PointerType>()) {
467 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
468 PT->getPointeeType()->isObjCQualifiedIdType())
469 return true;
470 }
471 return false;
472 }
473 bool PointerTypeTakesAnyBlockArguments(QualType QT);
474 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
475 void GetExtentOfArgList(const char *Name, const char *&LParen,
476 const char *&RParen);
477
478 void QuoteDoublequotes(std::string &From, std::string &To) {
479 for (unsigned i = 0; i < From.length(); i++) {
480 if (From[i] == '"')
481 To += "\\\"";
482 else
483 To += From[i];
484 }
485 }
486
487 QualType getSimpleFunctionType(QualType result,
488 const QualType *args,
489 unsigned numArgs,
490 bool variadic = false) {
491 if (result == Context->getObjCInstanceType())
492 result = Context->getObjCIdType();
493 FunctionProtoType::ExtProtoInfo fpi;
494 fpi.Variadic = variadic;
495 return Context->getFunctionType(result, args, numArgs, fpi);
496 }
497
498 // Helper function: create a CStyleCastExpr with trivial type source info.
499 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
500 CastKind Kind, Expr *E) {
501 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
502 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
503 SourceLocation(), SourceLocation());
504 }
505 };
506
507}
508
509void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
510 NamedDecl *D) {
511 if (const FunctionProtoType *fproto
512 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
513 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
514 E = fproto->arg_type_end(); I && (I != E); ++I)
515 if (isTopLevelBlockPointerType(*I)) {
516 // All the args are checked/rewritten. Don't call twice!
517 RewriteBlockPointerDecl(D);
518 break;
519 }
520 }
521}
522
523void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
524 const PointerType *PT = funcType->getAs<PointerType>();
525 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
526 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
527}
528
529static bool IsHeaderFile(const std::string &Filename) {
530 std::string::size_type DotPos = Filename.rfind('.');
531
532 if (DotPos == std::string::npos) {
533 // no file extension
534 return false;
535 }
536
537 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
538 // C header: .h
539 // C++ header: .hh or .H;
540 return Ext == "h" || Ext == "hh" || Ext == "H";
541}
542
543RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
544 DiagnosticsEngine &D, const LangOptions &LOpts,
545 bool silenceMacroWarn)
546 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
547 SilenceRewriteMacroWarning(silenceMacroWarn) {
548 IsHeader = IsHeaderFile(inFile);
549 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
550 "rewriting sub-expression within a macro (may not be correct)");
551 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
552 DiagnosticsEngine::Warning,
553 "rewriter doesn't support user-specified control flow semantics "
554 "for @try/@finally (code may not execute properly)");
555}
556
557ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
558 raw_ostream* OS,
559 DiagnosticsEngine &Diags,
560 const LangOptions &LOpts,
561 bool SilenceRewriteMacroWarning) {
562 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
563}
564
565void RewriteModernObjC::InitializeCommon(ASTContext &context) {
566 Context = &context;
567 SM = &Context->getSourceManager();
568 TUDecl = Context->getTranslationUnitDecl();
569 MsgSendFunctionDecl = 0;
570 MsgSendSuperFunctionDecl = 0;
571 MsgSendStretFunctionDecl = 0;
572 MsgSendSuperStretFunctionDecl = 0;
573 MsgSendFpretFunctionDecl = 0;
574 GetClassFunctionDecl = 0;
575 GetMetaClassFunctionDecl = 0;
576 GetSuperClassFunctionDecl = 0;
577 SelGetUidFunctionDecl = 0;
578 CFStringFunctionDecl = 0;
579 ConstantStringClassReference = 0;
580 NSStringRecord = 0;
581 CurMethodDef = 0;
582 CurFunctionDef = 0;
583 CurFunctionDeclToDeclareForBlock = 0;
584 GlobalVarDecl = 0;
585 SuperStructDecl = 0;
586 ProtocolTypeDecl = 0;
587 ConstantStringDecl = 0;
588 BcLabelCount = 0;
589 SuperContructorFunctionDecl = 0;
590 NumObjCStringLiterals = 0;
591 PropParentMap = 0;
592 CurrentBody = 0;
593 DisableReplaceStmt = false;
594 objc_impl_method = false;
595
596 // Get the ID and start/end of the main file.
597 MainFileID = SM->getMainFileID();
598 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
599 MainFileStart = MainBuf->getBufferStart();
600 MainFileEnd = MainBuf->getBufferEnd();
601
602 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
603}
604
605//===----------------------------------------------------------------------===//
606// Top Level Driver Code
607//===----------------------------------------------------------------------===//
608
609void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
610 if (Diags.hasErrorOccurred())
611 return;
612
613 // Two cases: either the decl could be in the main file, or it could be in a
614 // #included file. If the former, rewrite it now. If the later, check to see
615 // if we rewrote the #include/#import.
616 SourceLocation Loc = D->getLocation();
617 Loc = SM->getExpansionLoc(Loc);
618
619 // If this is for a builtin, ignore it.
620 if (Loc.isInvalid()) return;
621
622 // Look for built-in declarations that we need to refer during the rewrite.
623 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
624 RewriteFunctionDecl(FD);
625 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
626 // declared in <Foundation/NSString.h>
627 if (FVD->getName() == "_NSConstantStringClassReference") {
628 ConstantStringClassReference = FVD;
629 return;
630 }
631 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
632 if (ID->isThisDeclarationADefinition())
633 RewriteInterfaceDecl(ID);
634 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
635 RewriteCategoryDecl(CD);
636 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
637 if (PD->isThisDeclarationADefinition())
638 RewriteProtocolDecl(PD);
639 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
640 // Recurse into linkage specifications
641 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
642 DIEnd = LSD->decls_end();
643 DI != DIEnd; ) {
644 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
645 if (!IFace->isThisDeclarationADefinition()) {
646 SmallVector<Decl *, 8> DG;
647 SourceLocation StartLoc = IFace->getLocStart();
648 do {
649 if (isa<ObjCInterfaceDecl>(*DI) &&
650 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
651 StartLoc == (*DI)->getLocStart())
652 DG.push_back(*DI);
653 else
654 break;
655
656 ++DI;
657 } while (DI != DIEnd);
658 RewriteForwardClassDecl(DG);
659 continue;
660 }
661 }
662
663 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
664 if (!Proto->isThisDeclarationADefinition()) {
665 SmallVector<Decl *, 8> DG;
666 SourceLocation StartLoc = Proto->getLocStart();
667 do {
668 if (isa<ObjCProtocolDecl>(*DI) &&
669 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
670 StartLoc == (*DI)->getLocStart())
671 DG.push_back(*DI);
672 else
673 break;
674
675 ++DI;
676 } while (DI != DIEnd);
677 RewriteForwardProtocolDecl(DG);
678 continue;
679 }
680 }
681
682 HandleTopLevelSingleDecl(*DI);
683 ++DI;
684 }
685 }
686 // If we have a decl in the main file, see if we should rewrite it.
687 if (SM->isFromMainFile(Loc))
688 return HandleDeclInMainFile(D);
689}
690
691//===----------------------------------------------------------------------===//
692// Syntactic (non-AST) Rewriting Code
693//===----------------------------------------------------------------------===//
694
695void RewriteModernObjC::RewriteInclude() {
696 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
697 StringRef MainBuf = SM->getBufferData(MainFileID);
698 const char *MainBufStart = MainBuf.begin();
699 const char *MainBufEnd = MainBuf.end();
700 size_t ImportLen = strlen("import");
701
702 // Loop over the whole file, looking for includes.
703 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
704 if (*BufPtr == '#') {
705 if (++BufPtr == MainBufEnd)
706 return;
707 while (*BufPtr == ' ' || *BufPtr == '\t')
708 if (++BufPtr == MainBufEnd)
709 return;
710 if (!strncmp(BufPtr, "import", ImportLen)) {
711 // replace import with include
712 SourceLocation ImportLoc =
713 LocStart.getLocWithOffset(BufPtr-MainBufStart);
714 ReplaceText(ImportLoc, ImportLen, "include");
715 BufPtr += ImportLen;
716 }
717 }
718 }
719}
720
721static std::string getIvarAccessString(ObjCIvarDecl *OID) {
722 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
723 std::string S;
724 S = "((struct ";
725 S += ClassDecl->getIdentifier()->getName();
726 S += "_IMPL *)self)->";
727 S += OID->getName();
728 return S;
729}
730
731void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
732 ObjCImplementationDecl *IMD,
733 ObjCCategoryImplDecl *CID) {
734 static bool objcGetPropertyDefined = false;
735 static bool objcSetPropertyDefined = false;
736 SourceLocation startLoc = PID->getLocStart();
737 InsertText(startLoc, "// ");
738 const char *startBuf = SM->getCharacterData(startLoc);
739 assert((*startBuf == '@') && "bogus @synthesize location");
740 const char *semiBuf = strchr(startBuf, ';');
741 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
742 SourceLocation onePastSemiLoc =
743 startLoc.getLocWithOffset(semiBuf-startBuf+1);
744
745 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
746 return; // FIXME: is this correct?
747
748 // Generate the 'getter' function.
749 ObjCPropertyDecl *PD = PID->getPropertyDecl();
750 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
751
752 if (!OID)
753 return;
754 unsigned Attributes = PD->getPropertyAttributes();
755 if (!PD->getGetterMethodDecl()->isDefined()) {
756 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
757 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
758 ObjCPropertyDecl::OBJC_PR_copy));
759 std::string Getr;
760 if (GenGetProperty && !objcGetPropertyDefined) {
761 objcGetPropertyDefined = true;
762 // FIXME. Is this attribute correct in all cases?
763 Getr = "\nextern \"C\" __declspec(dllimport) "
764 "id objc_getProperty(id, SEL, long, bool);\n";
765 }
766 RewriteObjCMethodDecl(OID->getContainingInterface(),
767 PD->getGetterMethodDecl(), Getr);
768 Getr += "{ ";
769 // Synthesize an explicit cast to gain access to the ivar.
770 // See objc-act.c:objc_synthesize_new_getter() for details.
771 if (GenGetProperty) {
772 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
773 Getr += "typedef ";
774 const FunctionType *FPRetType = 0;
775 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
776 FPRetType);
777 Getr += " _TYPE";
778 if (FPRetType) {
779 Getr += ")"; // close the precedence "scope" for "*".
780
781 // Now, emit the argument types (if any).
782 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
783 Getr += "(";
784 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
785 if (i) Getr += ", ";
786 std::string ParamStr = FT->getArgType(i).getAsString(
787 Context->getPrintingPolicy());
788 Getr += ParamStr;
789 }
790 if (FT->isVariadic()) {
791 if (FT->getNumArgs()) Getr += ", ";
792 Getr += "...";
793 }
794 Getr += ")";
795 } else
796 Getr += "()";
797 }
798 Getr += ";\n";
799 Getr += "return (_TYPE)";
800 Getr += "objc_getProperty(self, _cmd, ";
801 RewriteIvarOffsetComputation(OID, Getr);
802 Getr += ", 1)";
803 }
804 else
805 Getr += "return " + getIvarAccessString(OID);
806 Getr += "; }";
807 InsertText(onePastSemiLoc, Getr);
808 }
809
810 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
811 return;
812
813 // Generate the 'setter' function.
814 std::string Setr;
815 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
816 ObjCPropertyDecl::OBJC_PR_copy);
817 if (GenSetProperty && !objcSetPropertyDefined) {
818 objcSetPropertyDefined = true;
819 // FIXME. Is this attribute correct in all cases?
820 Setr = "\nextern \"C\" __declspec(dllimport) "
821 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
822 }
823
824 RewriteObjCMethodDecl(OID->getContainingInterface(),
825 PD->getSetterMethodDecl(), Setr);
826 Setr += "{ ";
827 // Synthesize an explicit cast to initialize the ivar.
828 // See objc-act.c:objc_synthesize_new_setter() for details.
829 if (GenSetProperty) {
830 Setr += "objc_setProperty (self, _cmd, ";
831 RewriteIvarOffsetComputation(OID, Setr);
832 Setr += ", (id)";
833 Setr += PD->getName();
834 Setr += ", ";
835 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
836 Setr += "0, ";
837 else
838 Setr += "1, ";
839 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
840 Setr += "1)";
841 else
842 Setr += "0)";
843 }
844 else {
845 Setr += getIvarAccessString(OID) + " = ";
846 Setr += PD->getName();
847 }
848 Setr += "; }";
849 InsertText(onePastSemiLoc, Setr);
850}
851
852static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
853 std::string &typedefString) {
854 typedefString += "#ifndef _REWRITER_typedef_";
855 typedefString += ForwardDecl->getNameAsString();
856 typedefString += "\n";
857 typedefString += "#define _REWRITER_typedef_";
858 typedefString += ForwardDecl->getNameAsString();
859 typedefString += "\n";
860 typedefString += "typedef struct objc_object ";
861 typedefString += ForwardDecl->getNameAsString();
862 typedefString += ";\n#endif\n";
863}
864
865void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
866 const std::string &typedefString) {
867 SourceLocation startLoc = ClassDecl->getLocStart();
868 const char *startBuf = SM->getCharacterData(startLoc);
869 const char *semiPtr = strchr(startBuf, ';');
870 // Replace the @class with typedefs corresponding to the classes.
871 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
872}
873
874void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
875 std::string typedefString;
876 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
877 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
878 if (I == D.begin()) {
879 // Translate to typedef's that forward reference structs with the same name
880 // as the class. As a convenience, we include the original declaration
881 // as a comment.
882 typedefString += "// @class ";
883 typedefString += ForwardDecl->getNameAsString();
884 typedefString += ";\n";
885 }
886 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
887 }
888 DeclGroupRef::iterator I = D.begin();
889 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
890}
891
892void RewriteModernObjC::RewriteForwardClassDecl(
893 const llvm::SmallVector<Decl*, 8> &D) {
894 std::string typedefString;
895 for (unsigned i = 0; i < D.size(); i++) {
896 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
897 if (i == 0) {
898 typedefString += "// @class ";
899 typedefString += ForwardDecl->getNameAsString();
900 typedefString += ";\n";
901 }
902 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
903 }
904 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
905}
906
907void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
908 // When method is a synthesized one, such as a getter/setter there is
909 // nothing to rewrite.
910 if (Method->isImplicit())
911 return;
912 SourceLocation LocStart = Method->getLocStart();
913 SourceLocation LocEnd = Method->getLocEnd();
914
915 if (SM->getExpansionLineNumber(LocEnd) >
916 SM->getExpansionLineNumber(LocStart)) {
917 InsertText(LocStart, "#if 0\n");
918 ReplaceText(LocEnd, 1, ";\n#endif\n");
919 } else {
920 InsertText(LocStart, "// ");
921 }
922}
923
924void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
925 SourceLocation Loc = prop->getAtLoc();
926
927 ReplaceText(Loc, 0, "// ");
928 // FIXME: handle properties that are declared across multiple lines.
929}
930
931void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
932 SourceLocation LocStart = CatDecl->getLocStart();
933
934 // FIXME: handle category headers that are declared across multiple lines.
935 ReplaceText(LocStart, 0, "// ");
936
937 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
938 E = CatDecl->prop_end(); I != E; ++I)
939 RewriteProperty(*I);
940
941 for (ObjCCategoryDecl::instmeth_iterator
942 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
943 I != E; ++I)
944 RewriteMethodDeclaration(*I);
945 for (ObjCCategoryDecl::classmeth_iterator
946 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
947 I != E; ++I)
948 RewriteMethodDeclaration(*I);
949
950 // Lastly, comment out the @end.
951 ReplaceText(CatDecl->getAtEndRange().getBegin(),
952 strlen("@end"), "/* @end */");
953}
954
955void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
956 SourceLocation LocStart = PDecl->getLocStart();
957 assert(PDecl->isThisDeclarationADefinition());
958
959 // FIXME: handle protocol headers that are declared across multiple lines.
960 ReplaceText(LocStart, 0, "// ");
961
962 for (ObjCProtocolDecl::instmeth_iterator
963 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
964 I != E; ++I)
965 RewriteMethodDeclaration(*I);
966 for (ObjCProtocolDecl::classmeth_iterator
967 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
968 I != E; ++I)
969 RewriteMethodDeclaration(*I);
970
971 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
972 E = PDecl->prop_end(); I != E; ++I)
973 RewriteProperty(*I);
974
975 // Lastly, comment out the @end.
976 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
977 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
978
979 // Must comment out @optional/@required
980 const char *startBuf = SM->getCharacterData(LocStart);
981 const char *endBuf = SM->getCharacterData(LocEnd);
982 for (const char *p = startBuf; p < endBuf; p++) {
983 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
984 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
985 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
986
987 }
988 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
989 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
990 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
991
992 }
993 }
994}
995
996void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
997 SourceLocation LocStart = (*D.begin())->getLocStart();
998 if (LocStart.isInvalid())
999 llvm_unreachable("Invalid SourceLocation");
1000 // FIXME: handle forward protocol that are declared across multiple lines.
1001 ReplaceText(LocStart, 0, "// ");
1002}
1003
1004void
1005RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1006 SourceLocation LocStart = DG[0]->getLocStart();
1007 if (LocStart.isInvalid())
1008 llvm_unreachable("Invalid SourceLocation");
1009 // FIXME: handle forward protocol that are declared across multiple lines.
1010 ReplaceText(LocStart, 0, "// ");
1011}
1012
1013void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1014 const FunctionType *&FPRetType) {
1015 if (T->isObjCQualifiedIdType())
1016 ResultStr += "id";
1017 else if (T->isFunctionPointerType() ||
1018 T->isBlockPointerType()) {
1019 // needs special handling, since pointer-to-functions have special
1020 // syntax (where a decaration models use).
1021 QualType retType = T;
1022 QualType PointeeTy;
1023 if (const PointerType* PT = retType->getAs<PointerType>())
1024 PointeeTy = PT->getPointeeType();
1025 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1026 PointeeTy = BPT->getPointeeType();
1027 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1028 ResultStr += FPRetType->getResultType().getAsString(
1029 Context->getPrintingPolicy());
1030 ResultStr += "(*";
1031 }
1032 } else
1033 ResultStr += T.getAsString(Context->getPrintingPolicy());
1034}
1035
1036void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1037 ObjCMethodDecl *OMD,
1038 std::string &ResultStr) {
1039 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1040 const FunctionType *FPRetType = 0;
1041 ResultStr += "\nstatic ";
1042 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1043 ResultStr += " ";
1044
1045 // Unique method name
1046 std::string NameStr;
1047
1048 if (OMD->isInstanceMethod())
1049 NameStr += "_I_";
1050 else
1051 NameStr += "_C_";
1052
1053 NameStr += IDecl->getNameAsString();
1054 NameStr += "_";
1055
1056 if (ObjCCategoryImplDecl *CID =
1057 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1058 NameStr += CID->getNameAsString();
1059 NameStr += "_";
1060 }
1061 // Append selector names, replacing ':' with '_'
1062 {
1063 std::string selString = OMD->getSelector().getAsString();
1064 int len = selString.size();
1065 for (int i = 0; i < len; i++)
1066 if (selString[i] == ':')
1067 selString[i] = '_';
1068 NameStr += selString;
1069 }
1070 // Remember this name for metadata emission
1071 MethodInternalNames[OMD] = NameStr;
1072 ResultStr += NameStr;
1073
1074 // Rewrite arguments
1075 ResultStr += "(";
1076
1077 // invisible arguments
1078 if (OMD->isInstanceMethod()) {
1079 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1080 selfTy = Context->getPointerType(selfTy);
1081 if (!LangOpts.MicrosoftExt) {
1082 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1083 ResultStr += "struct ";
1084 }
1085 // When rewriting for Microsoft, explicitly omit the structure name.
1086 ResultStr += IDecl->getNameAsString();
1087 ResultStr += " *";
1088 }
1089 else
1090 ResultStr += Context->getObjCClassType().getAsString(
1091 Context->getPrintingPolicy());
1092
1093 ResultStr += " self, ";
1094 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1095 ResultStr += " _cmd";
1096
1097 // Method arguments.
1098 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1099 E = OMD->param_end(); PI != E; ++PI) {
1100 ParmVarDecl *PDecl = *PI;
1101 ResultStr += ", ";
1102 if (PDecl->getType()->isObjCQualifiedIdType()) {
1103 ResultStr += "id ";
1104 ResultStr += PDecl->getNameAsString();
1105 } else {
1106 std::string Name = PDecl->getNameAsString();
1107 QualType QT = PDecl->getType();
1108 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1109 if (convertBlockPointerToFunctionPointer(QT))
1110 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1111 else
1112 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
1113 ResultStr += Name;
1114 }
1115 }
1116 if (OMD->isVariadic())
1117 ResultStr += ", ...";
1118 ResultStr += ") ";
1119
1120 if (FPRetType) {
1121 ResultStr += ")"; // close the precedence "scope" for "*".
1122
1123 // Now, emit the argument types (if any).
1124 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1125 ResultStr += "(";
1126 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1127 if (i) ResultStr += ", ";
1128 std::string ParamStr = FT->getArgType(i).getAsString(
1129 Context->getPrintingPolicy());
1130 ResultStr += ParamStr;
1131 }
1132 if (FT->isVariadic()) {
1133 if (FT->getNumArgs()) ResultStr += ", ";
1134 ResultStr += "...";
1135 }
1136 ResultStr += ")";
1137 } else {
1138 ResultStr += "()";
1139 }
1140 }
1141}
1142void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1143 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1144 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1145
1146 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
1147
1148 for (ObjCCategoryImplDecl::instmeth_iterator
1149 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1150 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1151 I != E; ++I) {
1152 std::string ResultStr;
1153 ObjCMethodDecl *OMD = *I;
1154 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1155 SourceLocation LocStart = OMD->getLocStart();
1156 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1157
1158 const char *startBuf = SM->getCharacterData(LocStart);
1159 const char *endBuf = SM->getCharacterData(LocEnd);
1160 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1161 }
1162
1163 for (ObjCCategoryImplDecl::classmeth_iterator
1164 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1165 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1166 I != E; ++I) {
1167 std::string ResultStr;
1168 ObjCMethodDecl *OMD = *I;
1169 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1170 SourceLocation LocStart = OMD->getLocStart();
1171 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1172
1173 const char *startBuf = SM->getCharacterData(LocStart);
1174 const char *endBuf = SM->getCharacterData(LocEnd);
1175 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1176 }
1177 for (ObjCCategoryImplDecl::propimpl_iterator
1178 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1179 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1180 I != E; ++I) {
1181 RewritePropertyImplDecl(*I, IMD, CID);
1182 }
1183
1184 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1185}
1186
1187void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1188 std::string ResultStr;
1189 if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
1190 // we haven't seen a forward decl - generate a typedef.
1191 ResultStr = "#ifndef _REWRITER_typedef_";
1192 ResultStr += ClassDecl->getNameAsString();
1193 ResultStr += "\n";
1194 ResultStr += "#define _REWRITER_typedef_";
1195 ResultStr += ClassDecl->getNameAsString();
1196 ResultStr += "\n";
1197 ResultStr += "typedef struct objc_object ";
1198 ResultStr += ClassDecl->getNameAsString();
1199 ResultStr += ";\n#endif\n";
1200 // Mark this typedef as having been generated.
1201 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
1202 }
1203 RewriteObjCInternalStruct(ClassDecl, ResultStr);
1204
1205 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1206 E = ClassDecl->prop_end(); I != E; ++I)
1207 RewriteProperty(*I);
1208 for (ObjCInterfaceDecl::instmeth_iterator
1209 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
1210 I != E; ++I)
1211 RewriteMethodDeclaration(*I);
1212 for (ObjCInterfaceDecl::classmeth_iterator
1213 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
1214 I != E; ++I)
1215 RewriteMethodDeclaration(*I);
1216
1217 // Lastly, comment out the @end.
1218 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1219 "/* @end */");
1220}
1221
1222Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1223 SourceRange OldRange = PseudoOp->getSourceRange();
1224
1225 // We just magically know some things about the structure of this
1226 // expression.
1227 ObjCMessageExpr *OldMsg =
1228 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1229 PseudoOp->getNumSemanticExprs() - 1));
1230
1231 // Because the rewriter doesn't allow us to rewrite rewritten code,
1232 // we need to suppress rewriting the sub-statements.
1233 Expr *Base, *RHS;
1234 {
1235 DisableReplaceStmtScope S(*this);
1236
1237 // Rebuild the base expression if we have one.
1238 Base = 0;
1239 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1240 Base = OldMsg->getInstanceReceiver();
1241 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1242 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1243 }
1244
1245 // Rebuild the RHS.
1246 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1247 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1248 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1249 }
1250
1251 // TODO: avoid this copy.
1252 SmallVector<SourceLocation, 1> SelLocs;
1253 OldMsg->getSelectorLocs(SelLocs);
1254
1255 ObjCMessageExpr *NewMsg = 0;
1256 switch (OldMsg->getReceiverKind()) {
1257 case ObjCMessageExpr::Class:
1258 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1259 OldMsg->getValueKind(),
1260 OldMsg->getLeftLoc(),
1261 OldMsg->getClassReceiverTypeInfo(),
1262 OldMsg->getSelector(),
1263 SelLocs,
1264 OldMsg->getMethodDecl(),
1265 RHS,
1266 OldMsg->getRightLoc(),
1267 OldMsg->isImplicit());
1268 break;
1269
1270 case ObjCMessageExpr::Instance:
1271 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1272 OldMsg->getValueKind(),
1273 OldMsg->getLeftLoc(),
1274 Base,
1275 OldMsg->getSelector(),
1276 SelLocs,
1277 OldMsg->getMethodDecl(),
1278 RHS,
1279 OldMsg->getRightLoc(),
1280 OldMsg->isImplicit());
1281 break;
1282
1283 case ObjCMessageExpr::SuperClass:
1284 case ObjCMessageExpr::SuperInstance:
1285 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1286 OldMsg->getValueKind(),
1287 OldMsg->getLeftLoc(),
1288 OldMsg->getSuperLoc(),
1289 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1290 OldMsg->getSuperType(),
1291 OldMsg->getSelector(),
1292 SelLocs,
1293 OldMsg->getMethodDecl(),
1294 RHS,
1295 OldMsg->getRightLoc(),
1296 OldMsg->isImplicit());
1297 break;
1298 }
1299
1300 Stmt *Replacement = SynthMessageExpr(NewMsg);
1301 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1302 return Replacement;
1303}
1304
1305Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1306 SourceRange OldRange = PseudoOp->getSourceRange();
1307
1308 // We just magically know some things about the structure of this
1309 // expression.
1310 ObjCMessageExpr *OldMsg =
1311 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1312
1313 // Because the rewriter doesn't allow us to rewrite rewritten code,
1314 // we need to suppress rewriting the sub-statements.
1315 Expr *Base = 0;
1316 {
1317 DisableReplaceStmtScope S(*this);
1318
1319 // Rebuild the base expression if we have one.
1320 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1321 Base = OldMsg->getInstanceReceiver();
1322 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1323 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1324 }
1325 }
1326
1327 // Intentionally empty.
1328 SmallVector<SourceLocation, 1> SelLocs;
1329 SmallVector<Expr*, 1> Args;
1330
1331 ObjCMessageExpr *NewMsg = 0;
1332 switch (OldMsg->getReceiverKind()) {
1333 case ObjCMessageExpr::Class:
1334 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1335 OldMsg->getValueKind(),
1336 OldMsg->getLeftLoc(),
1337 OldMsg->getClassReceiverTypeInfo(),
1338 OldMsg->getSelector(),
1339 SelLocs,
1340 OldMsg->getMethodDecl(),
1341 Args,
1342 OldMsg->getRightLoc(),
1343 OldMsg->isImplicit());
1344 break;
1345
1346 case ObjCMessageExpr::Instance:
1347 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1348 OldMsg->getValueKind(),
1349 OldMsg->getLeftLoc(),
1350 Base,
1351 OldMsg->getSelector(),
1352 SelLocs,
1353 OldMsg->getMethodDecl(),
1354 Args,
1355 OldMsg->getRightLoc(),
1356 OldMsg->isImplicit());
1357 break;
1358
1359 case ObjCMessageExpr::SuperClass:
1360 case ObjCMessageExpr::SuperInstance:
1361 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1362 OldMsg->getValueKind(),
1363 OldMsg->getLeftLoc(),
1364 OldMsg->getSuperLoc(),
1365 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1366 OldMsg->getSuperType(),
1367 OldMsg->getSelector(),
1368 SelLocs,
1369 OldMsg->getMethodDecl(),
1370 Args,
1371 OldMsg->getRightLoc(),
1372 OldMsg->isImplicit());
1373 break;
1374 }
1375
1376 Stmt *Replacement = SynthMessageExpr(NewMsg);
1377 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1378 return Replacement;
1379}
1380
1381/// SynthCountByEnumWithState - To print:
1382/// ((unsigned int (*)
1383/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1384/// (void *)objc_msgSend)((id)l_collection,
1385/// sel_registerName(
1386/// "countByEnumeratingWithState:objects:count:"),
1387/// &enumState,
1388/// (id *)__rw_items, (unsigned int)16)
1389///
1390void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1391 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1392 "id *, unsigned int))(void *)objc_msgSend)";
1393 buf += "\n\t\t";
1394 buf += "((id)l_collection,\n\t\t";
1395 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1396 buf += "\n\t\t";
1397 buf += "&enumState, "
1398 "(id *)__rw_items, (unsigned int)16)";
1399}
1400
1401/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1402/// statement to exit to its outer synthesized loop.
1403///
1404Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1405 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1406 return S;
1407 // replace break with goto __break_label
1408 std::string buf;
1409
1410 SourceLocation startLoc = S->getLocStart();
1411 buf = "goto __break_label_";
1412 buf += utostr(ObjCBcLabelNo.back());
1413 ReplaceText(startLoc, strlen("break"), buf);
1414
1415 return 0;
1416}
1417
1418/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1419/// statement to continue with its inner synthesized loop.
1420///
1421Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1422 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1423 return S;
1424 // replace continue with goto __continue_label
1425 std::string buf;
1426
1427 SourceLocation startLoc = S->getLocStart();
1428 buf = "goto __continue_label_";
1429 buf += utostr(ObjCBcLabelNo.back());
1430 ReplaceText(startLoc, strlen("continue"), buf);
1431
1432 return 0;
1433}
1434
1435/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1436/// It rewrites:
1437/// for ( type elem in collection) { stmts; }
1438
1439/// Into:
1440/// {
1441/// type elem;
1442/// struct __objcFastEnumerationState enumState = { 0 };
1443/// id __rw_items[16];
1444/// id l_collection = (id)collection;
1445/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1446/// objects:__rw_items count:16];
1447/// if (limit) {
1448/// unsigned long startMutations = *enumState.mutationsPtr;
1449/// do {
1450/// unsigned long counter = 0;
1451/// do {
1452/// if (startMutations != *enumState.mutationsPtr)
1453/// objc_enumerationMutation(l_collection);
1454/// elem = (type)enumState.itemsPtr[counter++];
1455/// stmts;
1456/// __continue_label: ;
1457/// } while (counter < limit);
1458/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1459/// objects:__rw_items count:16]);
1460/// elem = nil;
1461/// __break_label: ;
1462/// }
1463/// else
1464/// elem = nil;
1465/// }
1466///
1467Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1468 SourceLocation OrigEnd) {
1469 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1470 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1471 "ObjCForCollectionStmt Statement stack mismatch");
1472 assert(!ObjCBcLabelNo.empty() &&
1473 "ObjCForCollectionStmt - Label No stack empty");
1474
1475 SourceLocation startLoc = S->getLocStart();
1476 const char *startBuf = SM->getCharacterData(startLoc);
1477 StringRef elementName;
1478 std::string elementTypeAsString;
1479 std::string buf;
1480 buf = "\n{\n\t";
1481 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1482 // type elem;
1483 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1484 QualType ElementType = cast<ValueDecl>(D)->getType();
1485 if (ElementType->isObjCQualifiedIdType() ||
1486 ElementType->isObjCQualifiedInterfaceType())
1487 // Simply use 'id' for all qualified types.
1488 elementTypeAsString = "id";
1489 else
1490 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1491 buf += elementTypeAsString;
1492 buf += " ";
1493 elementName = D->getName();
1494 buf += elementName;
1495 buf += ";\n\t";
1496 }
1497 else {
1498 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1499 elementName = DR->getDecl()->getName();
1500 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1501 if (VD->getType()->isObjCQualifiedIdType() ||
1502 VD->getType()->isObjCQualifiedInterfaceType())
1503 // Simply use 'id' for all qualified types.
1504 elementTypeAsString = "id";
1505 else
1506 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1507 }
1508
1509 // struct __objcFastEnumerationState enumState = { 0 };
1510 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1511 // id __rw_items[16];
1512 buf += "id __rw_items[16];\n\t";
1513 // id l_collection = (id)
1514 buf += "id l_collection = (id)";
1515 // Find start location of 'collection' the hard way!
1516 const char *startCollectionBuf = startBuf;
1517 startCollectionBuf += 3; // skip 'for'
1518 startCollectionBuf = strchr(startCollectionBuf, '(');
1519 startCollectionBuf++; // skip '('
1520 // find 'in' and skip it.
1521 while (*startCollectionBuf != ' ' ||
1522 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1523 (*(startCollectionBuf+3) != ' ' &&
1524 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1525 startCollectionBuf++;
1526 startCollectionBuf += 3;
1527
1528 // Replace: "for (type element in" with string constructed thus far.
1529 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1530 // Replace ')' in for '(' type elem in collection ')' with ';'
1531 SourceLocation rightParenLoc = S->getRParenLoc();
1532 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1533 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1534 buf = ";\n\t";
1535
1536 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1537 // objects:__rw_items count:16];
1538 // which is synthesized into:
1539 // unsigned int limit =
1540 // ((unsigned int (*)
1541 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1542 // (void *)objc_msgSend)((id)l_collection,
1543 // sel_registerName(
1544 // "countByEnumeratingWithState:objects:count:"),
1545 // (struct __objcFastEnumerationState *)&state,
1546 // (id *)__rw_items, (unsigned int)16);
1547 buf += "unsigned long limit =\n\t\t";
1548 SynthCountByEnumWithState(buf);
1549 buf += ";\n\t";
1550 /// if (limit) {
1551 /// unsigned long startMutations = *enumState.mutationsPtr;
1552 /// do {
1553 /// unsigned long counter = 0;
1554 /// do {
1555 /// if (startMutations != *enumState.mutationsPtr)
1556 /// objc_enumerationMutation(l_collection);
1557 /// elem = (type)enumState.itemsPtr[counter++];
1558 buf += "if (limit) {\n\t";
1559 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1560 buf += "do {\n\t\t";
1561 buf += "unsigned long counter = 0;\n\t\t";
1562 buf += "do {\n\t\t\t";
1563 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1564 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1565 buf += elementName;
1566 buf += " = (";
1567 buf += elementTypeAsString;
1568 buf += ")enumState.itemsPtr[counter++];";
1569 // Replace ')' in for '(' type elem in collection ')' with all of these.
1570 ReplaceText(lparenLoc, 1, buf);
1571
1572 /// __continue_label: ;
1573 /// } while (counter < limit);
1574 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1575 /// objects:__rw_items count:16]);
1576 /// elem = nil;
1577 /// __break_label: ;
1578 /// }
1579 /// else
1580 /// elem = nil;
1581 /// }
1582 ///
1583 buf = ";\n\t";
1584 buf += "__continue_label_";
1585 buf += utostr(ObjCBcLabelNo.back());
1586 buf += ": ;";
1587 buf += "\n\t\t";
1588 buf += "} while (counter < limit);\n\t";
1589 buf += "} while (limit = ";
1590 SynthCountByEnumWithState(buf);
1591 buf += ");\n\t";
1592 buf += elementName;
1593 buf += " = ((";
1594 buf += elementTypeAsString;
1595 buf += ")0);\n\t";
1596 buf += "__break_label_";
1597 buf += utostr(ObjCBcLabelNo.back());
1598 buf += ": ;\n\t";
1599 buf += "}\n\t";
1600 buf += "else\n\t\t";
1601 buf += elementName;
1602 buf += " = ((";
1603 buf += elementTypeAsString;
1604 buf += ")0);\n\t";
1605 buf += "}\n";
1606
1607 // Insert all these *after* the statement body.
1608 // FIXME: If this should support Obj-C++, support CXXTryStmt
1609 if (isa<CompoundStmt>(S->getBody())) {
1610 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1611 InsertText(endBodyLoc, buf);
1612 } else {
1613 /* Need to treat single statements specially. For example:
1614 *
1615 * for (A *a in b) if (stuff()) break;
1616 * for (A *a in b) xxxyy;
1617 *
1618 * The following code simply scans ahead to the semi to find the actual end.
1619 */
1620 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1621 const char *semiBuf = strchr(stmtBuf, ';');
1622 assert(semiBuf && "Can't find ';'");
1623 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1624 InsertText(endBodyLoc, buf);
1625 }
1626 Stmts.pop_back();
1627 ObjCBcLabelNo.pop_back();
1628 return 0;
1629}
1630
1631/// RewriteObjCSynchronizedStmt -
1632/// This routine rewrites @synchronized(expr) stmt;
1633/// into:
1634/// objc_sync_enter(expr);
1635/// @try stmt @finally { objc_sync_exit(expr); }
1636///
1637Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1638 // Get the start location and compute the semi location.
1639 SourceLocation startLoc = S->getLocStart();
1640 const char *startBuf = SM->getCharacterData(startLoc);
1641
1642 assert((*startBuf == '@') && "bogus @synchronized location");
1643
1644 std::string buf;
1645 buf = "objc_sync_enter((id)";
1646 const char *lparenBuf = startBuf;
1647 while (*lparenBuf != '(') lparenBuf++;
1648 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1649 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1650 // the sync expression is typically a message expression that's already
1651 // been rewritten! (which implies the SourceLocation's are invalid).
1652 SourceLocation endLoc = S->getSynchBody()->getLocStart();
1653 const char *endBuf = SM->getCharacterData(endLoc);
1654 while (*endBuf != ')') endBuf--;
1655 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1656 buf = ");\n";
1657 // declare a new scope with two variables, _stack and _rethrow.
1658 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1659 buf += "int buf[18/*32-bit i386*/];\n";
1660 buf += "char *pointers[4];} _stack;\n";
1661 buf += "id volatile _rethrow = 0;\n";
1662 buf += "objc_exception_try_enter(&_stack);\n";
1663 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1664 ReplaceText(rparenLoc, 1, buf);
1665 startLoc = S->getSynchBody()->getLocEnd();
1666 startBuf = SM->getCharacterData(startLoc);
1667
1668 assert((*startBuf == '}') && "bogus @synchronized block");
1669 SourceLocation lastCurlyLoc = startLoc;
1670 buf = "}\nelse {\n";
1671 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1672 buf += "}\n";
1673 buf += "{ /* implicit finally clause */\n";
1674 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1675
1676 std::string syncBuf;
1677 syncBuf += " objc_sync_exit(";
1678
1679 Expr *syncExpr = S->getSynchExpr();
1680 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1681 ? CK_BitCast :
1682 syncExpr->getType()->isBlockPointerType()
1683 ? CK_BlockPointerToObjCPointerCast
1684 : CK_CPointerToObjCPointerCast;
1685 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1686 CK, syncExpr);
1687 std::string syncExprBufS;
1688 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1689 syncExpr->printPretty(syncExprBuf, *Context, 0,
1690 PrintingPolicy(LangOpts));
1691 syncBuf += syncExprBuf.str();
1692 syncBuf += ");";
1693
1694 buf += syncBuf;
1695 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
1696 buf += "}\n";
1697 buf += "}";
1698
1699 ReplaceText(lastCurlyLoc, 1, buf);
1700
1701 bool hasReturns = false;
1702 HasReturnStmts(S->getSynchBody(), hasReturns);
1703 if (hasReturns)
1704 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1705
1706 return 0;
1707}
1708
1709void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1710{
1711 // Perform a bottom up traversal of all children.
1712 for (Stmt::child_range CI = S->children(); CI; ++CI)
1713 if (*CI)
1714 WarnAboutReturnGotoStmts(*CI);
1715
1716 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1717 Diags.Report(Context->getFullLoc(S->getLocStart()),
1718 TryFinallyContainsReturnDiag);
1719 }
1720 return;
1721}
1722
1723void RewriteModernObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1724{
1725 // Perform a bottom up traversal of all children.
1726 for (Stmt::child_range CI = S->children(); CI; ++CI)
1727 if (*CI)
1728 HasReturnStmts(*CI, hasReturns);
1729
1730 if (isa<ReturnStmt>(S))
1731 hasReturns = true;
1732 return;
1733}
1734
1735void RewriteModernObjC::RewriteTryReturnStmts(Stmt *S) {
1736 // Perform a bottom up traversal of all children.
1737 for (Stmt::child_range CI = S->children(); CI; ++CI)
1738 if (*CI) {
1739 RewriteTryReturnStmts(*CI);
1740 }
1741 if (isa<ReturnStmt>(S)) {
1742 SourceLocation startLoc = S->getLocStart();
1743 const char *startBuf = SM->getCharacterData(startLoc);
1744
1745 const char *semiBuf = strchr(startBuf, ';');
1746 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1747 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1748
1749 std::string buf;
1750 buf = "{ objc_exception_try_exit(&_stack); return";
1751
1752 ReplaceText(startLoc, 6, buf);
1753 InsertText(onePastSemiLoc, "}");
1754 }
1755 return;
1756}
1757
1758void RewriteModernObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1759 // Perform a bottom up traversal of all children.
1760 for (Stmt::child_range CI = S->children(); CI; ++CI)
1761 if (*CI) {
1762 RewriteSyncReturnStmts(*CI, syncExitBuf);
1763 }
1764 if (isa<ReturnStmt>(S)) {
1765 SourceLocation startLoc = S->getLocStart();
1766 const char *startBuf = SM->getCharacterData(startLoc);
1767
1768 const char *semiBuf = strchr(startBuf, ';');
1769 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1770 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1771
1772 std::string buf;
1773 buf = "{ objc_exception_try_exit(&_stack);";
1774 buf += syncExitBuf;
1775 buf += " return";
1776
1777 ReplaceText(startLoc, 6, buf);
1778 InsertText(onePastSemiLoc, "}");
1779 }
1780 return;
1781}
1782
1783Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1784 // Get the start location and compute the semi location.
1785 SourceLocation startLoc = S->getLocStart();
1786 const char *startBuf = SM->getCharacterData(startLoc);
1787
1788 assert((*startBuf == '@') && "bogus @try location");
1789
1790 std::string buf;
1791 // declare a new scope with two variables, _stack and _rethrow.
1792 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1793 buf += "int buf[18/*32-bit i386*/];\n";
1794 buf += "char *pointers[4];} _stack;\n";
1795 buf += "id volatile _rethrow = 0;\n";
1796 buf += "objc_exception_try_enter(&_stack);\n";
1797 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1798
1799 ReplaceText(startLoc, 4, buf);
1800
1801 startLoc = S->getTryBody()->getLocEnd();
1802 startBuf = SM->getCharacterData(startLoc);
1803
1804 assert((*startBuf == '}') && "bogus @try block");
1805
1806 SourceLocation lastCurlyLoc = startLoc;
1807 if (S->getNumCatchStmts()) {
1808 startLoc = startLoc.getLocWithOffset(1);
1809 buf = " /* @catch begin */ else {\n";
1810 buf += " id _caught = objc_exception_extract(&_stack);\n";
1811 buf += " objc_exception_try_enter (&_stack);\n";
1812 buf += " if (_setjmp(_stack.buf))\n";
1813 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1814 buf += " else { /* @catch continue */";
1815
1816 InsertText(startLoc, buf);
1817 } else { /* no catch list */
1818 buf = "}\nelse {\n";
1819 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1820 buf += "}";
1821 ReplaceText(lastCurlyLoc, 1, buf);
1822 }
1823 Stmt *lastCatchBody = 0;
1824 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1825 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1826 VarDecl *catchDecl = Catch->getCatchParamDecl();
1827
1828 if (I == 0)
1829 buf = "if ("; // we are generating code for the first catch clause
1830 else
1831 buf = "else if (";
1832 startLoc = Catch->getLocStart();
1833 startBuf = SM->getCharacterData(startLoc);
1834
1835 assert((*startBuf == '@') && "bogus @catch location");
1836
1837 const char *lParenLoc = strchr(startBuf, '(');
1838
1839 if (Catch->hasEllipsis()) {
1840 // Now rewrite the body...
1841 lastCatchBody = Catch->getCatchBody();
1842 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1843 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1844 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1845 "bogus @catch paren location");
1846 assert((*bodyBuf == '{') && "bogus @catch body location");
1847
1848 buf += "1) { id _tmp = _caught;";
1849 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1850 } else if (catchDecl) {
1851 QualType t = catchDecl->getType();
1852 if (t == Context->getObjCIdType()) {
1853 buf += "1) { ";
1854 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1855 } else if (const ObjCObjectPointerType *Ptr =
1856 t->getAs<ObjCObjectPointerType>()) {
1857 // Should be a pointer to a class.
1858 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1859 if (IDecl) {
1860 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1861 buf += IDecl->getNameAsString();
1862 buf += "\"), (struct objc_object *)_caught)) { ";
1863 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1864 }
1865 }
1866 // Now rewrite the body...
1867 lastCatchBody = Catch->getCatchBody();
1868 SourceLocation rParenLoc = Catch->getRParenLoc();
1869 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1870 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1871 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1872 assert((*rParenBuf == ')') && "bogus @catch paren location");
1873 assert((*bodyBuf == '{') && "bogus @catch body location");
1874
1875 // Here we replace ") {" with "= _caught;" (which initializes and
1876 // declares the @catch parameter).
1877 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1878 } else {
1879 llvm_unreachable("@catch rewrite bug");
1880 }
1881 }
1882 // Complete the catch list...
1883 if (lastCatchBody) {
1884 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1885 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1886 "bogus @catch body location");
1887
1888 // Insert the last (implicit) else clause *before* the right curly brace.
1889 bodyLoc = bodyLoc.getLocWithOffset(-1);
1890 buf = "} /* last catch end */\n";
1891 buf += "else {\n";
1892 buf += " _rethrow = _caught;\n";
1893 buf += " objc_exception_try_exit(&_stack);\n";
1894 buf += "} } /* @catch end */\n";
1895 if (!S->getFinallyStmt())
1896 buf += "}\n";
1897 InsertText(bodyLoc, buf);
1898
1899 // Set lastCurlyLoc
1900 lastCurlyLoc = lastCatchBody->getLocEnd();
1901 }
1902 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1903 startLoc = finalStmt->getLocStart();
1904 startBuf = SM->getCharacterData(startLoc);
1905 assert((*startBuf == '@') && "bogus @finally start");
1906
1907 ReplaceText(startLoc, 8, "/* @finally */");
1908
1909 Stmt *body = finalStmt->getFinallyBody();
1910 SourceLocation startLoc = body->getLocStart();
1911 SourceLocation endLoc = body->getLocEnd();
1912 assert(*SM->getCharacterData(startLoc) == '{' &&
1913 "bogus @finally body location");
1914 assert(*SM->getCharacterData(endLoc) == '}' &&
1915 "bogus @finally body location");
1916
1917 startLoc = startLoc.getLocWithOffset(1);
1918 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1919 endLoc = endLoc.getLocWithOffset(-1);
1920 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1921
1922 // Set lastCurlyLoc
1923 lastCurlyLoc = body->getLocEnd();
1924
1925 // Now check for any return/continue/go statements within the @try.
1926 WarnAboutReturnGotoStmts(S->getTryBody());
1927 } else { /* no finally clause - make sure we synthesize an implicit one */
1928 buf = "{ /* implicit finally clause */\n";
1929 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1930 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1931 buf += "}";
1932 ReplaceText(lastCurlyLoc, 1, buf);
1933
1934 // Now check for any return/continue/go statements within the @try.
1935 // The implicit finally clause won't called if the @try contains any
1936 // jump statements.
1937 bool hasReturns = false;
1938 HasReturnStmts(S->getTryBody(), hasReturns);
1939 if (hasReturns)
1940 RewriteTryReturnStmts(S->getTryBody());
1941 }
1942 // Now emit the final closing curly brace...
1943 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1944 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1945 return 0;
1946}
1947
1948// This can't be done with ReplaceStmt(S, ThrowExpr), since
1949// the throw expression is typically a message expression that's already
1950// been rewritten! (which implies the SourceLocation's are invalid).
1951Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1952 // Get the start location and compute the semi location.
1953 SourceLocation startLoc = S->getLocStart();
1954 const char *startBuf = SM->getCharacterData(startLoc);
1955
1956 assert((*startBuf == '@') && "bogus @throw location");
1957
1958 std::string buf;
1959 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1960 if (S->getThrowExpr())
1961 buf = "objc_exception_throw(";
1962 else // add an implicit argument
1963 buf = "objc_exception_throw(_caught";
1964
1965 // handle "@ throw" correctly.
1966 const char *wBuf = strchr(startBuf, 'w');
1967 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1968 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1969
1970 const char *semiBuf = strchr(startBuf, ';');
1971 assert((*semiBuf == ';') && "@throw: can't find ';'");
1972 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1973 ReplaceText(semiLoc, 1, ");");
1974 return 0;
1975}
1976
1977Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1978 // Create a new string expression.
1979 QualType StrType = Context->getPointerType(Context->CharTy);
1980 std::string StrEncoding;
1981 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1982 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1983 StringLiteral::Ascii, false,
1984 StrType, SourceLocation());
1985 ReplaceStmt(Exp, Replacement);
1986
1987 // Replace this subexpr in the parent.
1988 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1989 return Replacement;
1990}
1991
1992Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1993 if (!SelGetUidFunctionDecl)
1994 SynthSelGetUidFunctionDecl();
1995 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1996 // Create a call to sel_registerName("selName").
1997 SmallVector<Expr*, 8> SelExprs;
1998 QualType argType = Context->getPointerType(Context->CharTy);
1999 SelExprs.push_back(StringLiteral::Create(*Context,
2000 Exp->getSelector().getAsString(),
2001 StringLiteral::Ascii, false,
2002 argType, SourceLocation()));
2003 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2004 &SelExprs[0], SelExprs.size());
2005 ReplaceStmt(Exp, SelExp);
2006 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2007 return SelExp;
2008}
2009
2010CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2011 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2012 SourceLocation EndLoc) {
2013 // Get the type, we will need to reference it in a couple spots.
2014 QualType msgSendType = FD->getType();
2015
2016 // Create a reference to the objc_msgSend() declaration.
2017 DeclRefExpr *DRE =
2018 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
2019
2020 // Now, we cast the reference to a pointer to the objc_msgSend type.
2021 QualType pToFunc = Context->getPointerType(msgSendType);
2022 ImplicitCastExpr *ICE =
2023 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2024 DRE, 0, VK_RValue);
2025
2026 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2027
2028 CallExpr *Exp =
2029 new (Context) CallExpr(*Context, ICE, args, nargs,
2030 FT->getCallResultType(*Context),
2031 VK_RValue, EndLoc);
2032 return Exp;
2033}
2034
2035static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2036 const char *&startRef, const char *&endRef) {
2037 while (startBuf < endBuf) {
2038 if (*startBuf == '<')
2039 startRef = startBuf; // mark the start.
2040 if (*startBuf == '>') {
2041 if (startRef && *startRef == '<') {
2042 endRef = startBuf; // mark the end.
2043 return true;
2044 }
2045 return false;
2046 }
2047 startBuf++;
2048 }
2049 return false;
2050}
2051
2052static void scanToNextArgument(const char *&argRef) {
2053 int angle = 0;
2054 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2055 if (*argRef == '<')
2056 angle++;
2057 else if (*argRef == '>')
2058 angle--;
2059 argRef++;
2060 }
2061 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2062}
2063
2064bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2065 if (T->isObjCQualifiedIdType())
2066 return true;
2067 if (const PointerType *PT = T->getAs<PointerType>()) {
2068 if (PT->getPointeeType()->isObjCQualifiedIdType())
2069 return true;
2070 }
2071 if (T->isObjCObjectPointerType()) {
2072 T = T->getPointeeType();
2073 return T->isObjCQualifiedInterfaceType();
2074 }
2075 if (T->isArrayType()) {
2076 QualType ElemTy = Context->getBaseElementType(T);
2077 return needToScanForQualifiers(ElemTy);
2078 }
2079 return false;
2080}
2081
2082void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2083 QualType Type = E->getType();
2084 if (needToScanForQualifiers(Type)) {
2085 SourceLocation Loc, EndLoc;
2086
2087 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2088 Loc = ECE->getLParenLoc();
2089 EndLoc = ECE->getRParenLoc();
2090 } else {
2091 Loc = E->getLocStart();
2092 EndLoc = E->getLocEnd();
2093 }
2094 // This will defend against trying to rewrite synthesized expressions.
2095 if (Loc.isInvalid() || EndLoc.isInvalid())
2096 return;
2097
2098 const char *startBuf = SM->getCharacterData(Loc);
2099 const char *endBuf = SM->getCharacterData(EndLoc);
2100 const char *startRef = 0, *endRef = 0;
2101 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2102 // Get the locations of the startRef, endRef.
2103 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2104 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2105 // Comment out the protocol references.
2106 InsertText(LessLoc, "/*");
2107 InsertText(GreaterLoc, "*/");
2108 }
2109 }
2110}
2111
2112void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2113 SourceLocation Loc;
2114 QualType Type;
2115 const FunctionProtoType *proto = 0;
2116 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2117 Loc = VD->getLocation();
2118 Type = VD->getType();
2119 }
2120 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2121 Loc = FD->getLocation();
2122 // Check for ObjC 'id' and class types that have been adorned with protocol
2123 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2124 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2125 assert(funcType && "missing function type");
2126 proto = dyn_cast<FunctionProtoType>(funcType);
2127 if (!proto)
2128 return;
2129 Type = proto->getResultType();
2130 }
2131 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2132 Loc = FD->getLocation();
2133 Type = FD->getType();
2134 }
2135 else
2136 return;
2137
2138 if (needToScanForQualifiers(Type)) {
2139 // Since types are unique, we need to scan the buffer.
2140
2141 const char *endBuf = SM->getCharacterData(Loc);
2142 const char *startBuf = endBuf;
2143 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2144 startBuf--; // scan backward (from the decl location) for return type.
2145 const char *startRef = 0, *endRef = 0;
2146 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2147 // Get the locations of the startRef, endRef.
2148 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2149 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2150 // Comment out the protocol references.
2151 InsertText(LessLoc, "/*");
2152 InsertText(GreaterLoc, "*/");
2153 }
2154 }
2155 if (!proto)
2156 return; // most likely, was a variable
2157 // Now check arguments.
2158 const char *startBuf = SM->getCharacterData(Loc);
2159 const char *startFuncBuf = startBuf;
2160 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2161 if (needToScanForQualifiers(proto->getArgType(i))) {
2162 // Since types are unique, we need to scan the buffer.
2163
2164 const char *endBuf = startBuf;
2165 // scan forward (from the decl location) for argument types.
2166 scanToNextArgument(endBuf);
2167 const char *startRef = 0, *endRef = 0;
2168 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2169 // Get the locations of the startRef, endRef.
2170 SourceLocation LessLoc =
2171 Loc.getLocWithOffset(startRef-startFuncBuf);
2172 SourceLocation GreaterLoc =
2173 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2174 // Comment out the protocol references.
2175 InsertText(LessLoc, "/*");
2176 InsertText(GreaterLoc, "*/");
2177 }
2178 startBuf = ++endBuf;
2179 }
2180 else {
2181 // If the function name is derived from a macro expansion, then the
2182 // argument buffer will not follow the name. Need to speak with Chris.
2183 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2184 startBuf++; // scan forward (from the decl location) for argument types.
2185 startBuf++;
2186 }
2187 }
2188}
2189
2190void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2191 QualType QT = ND->getType();
2192 const Type* TypePtr = QT->getAs<Type>();
2193 if (!isa<TypeOfExprType>(TypePtr))
2194 return;
2195 while (isa<TypeOfExprType>(TypePtr)) {
2196 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2197 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2198 TypePtr = QT->getAs<Type>();
2199 }
2200 // FIXME. This will not work for multiple declarators; as in:
2201 // __typeof__(a) b,c,d;
2202 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2203 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2204 const char *startBuf = SM->getCharacterData(DeclLoc);
2205 if (ND->getInit()) {
2206 std::string Name(ND->getNameAsString());
2207 TypeAsString += " " + Name + " = ";
2208 Expr *E = ND->getInit();
2209 SourceLocation startLoc;
2210 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2211 startLoc = ECE->getLParenLoc();
2212 else
2213 startLoc = E->getLocStart();
2214 startLoc = SM->getExpansionLoc(startLoc);
2215 const char *endBuf = SM->getCharacterData(startLoc);
2216 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2217 }
2218 else {
2219 SourceLocation X = ND->getLocEnd();
2220 X = SM->getExpansionLoc(X);
2221 const char *endBuf = SM->getCharacterData(X);
2222 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2223 }
2224}
2225
2226// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2227void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2228 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2229 SmallVector<QualType, 16> ArgTys;
2230 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2231 QualType getFuncType =
2232 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2233 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2234 SourceLocation(),
2235 SourceLocation(),
2236 SelGetUidIdent, getFuncType, 0,
2237 SC_Extern,
2238 SC_None, false);
2239}
2240
2241void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2242 // declared in <objc/objc.h>
2243 if (FD->getIdentifier() &&
2244 FD->getName() == "sel_registerName") {
2245 SelGetUidFunctionDecl = FD;
2246 return;
2247 }
2248 RewriteObjCQualifiedInterfaceTypes(FD);
2249}
2250
2251void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2252 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2253 const char *argPtr = TypeString.c_str();
2254 if (!strchr(argPtr, '^')) {
2255 Str += TypeString;
2256 return;
2257 }
2258 while (*argPtr) {
2259 Str += (*argPtr == '^' ? '*' : *argPtr);
2260 argPtr++;
2261 }
2262}
2263
2264// FIXME. Consolidate this routine with RewriteBlockPointerType.
2265void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2266 ValueDecl *VD) {
2267 QualType Type = VD->getType();
2268 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2269 const char *argPtr = TypeString.c_str();
2270 int paren = 0;
2271 while (*argPtr) {
2272 switch (*argPtr) {
2273 case '(':
2274 Str += *argPtr;
2275 paren++;
2276 break;
2277 case ')':
2278 Str += *argPtr;
2279 paren--;
2280 break;
2281 case '^':
2282 Str += '*';
2283 if (paren == 1)
2284 Str += VD->getNameAsString();
2285 break;
2286 default:
2287 Str += *argPtr;
2288 break;
2289 }
2290 argPtr++;
2291 }
2292}
2293
2294
2295void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2296 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2297 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2298 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2299 if (!proto)
2300 return;
2301 QualType Type = proto->getResultType();
2302 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2303 FdStr += " ";
2304 FdStr += FD->getName();
2305 FdStr += "(";
2306 unsigned numArgs = proto->getNumArgs();
2307 for (unsigned i = 0; i < numArgs; i++) {
2308 QualType ArgType = proto->getArgType(i);
2309 RewriteBlockPointerType(FdStr, ArgType);
2310 if (i+1 < numArgs)
2311 FdStr += ", ";
2312 }
2313 FdStr += ");\n";
2314 InsertText(FunLocStart, FdStr);
2315 CurFunctionDeclToDeclareForBlock = 0;
2316}
2317
2318// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2319void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2320 if (SuperContructorFunctionDecl)
2321 return;
2322 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2323 SmallVector<QualType, 16> ArgTys;
2324 QualType argT = Context->getObjCIdType();
2325 assert(!argT.isNull() && "Can't find 'id' type");
2326 ArgTys.push_back(argT);
2327 ArgTys.push_back(argT);
2328 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2329 &ArgTys[0], ArgTys.size());
2330 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2331 SourceLocation(),
2332 SourceLocation(),
2333 msgSendIdent, msgSendType, 0,
2334 SC_Extern,
2335 SC_None, false);
2336}
2337
2338// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2339void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2340 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2341 SmallVector<QualType, 16> ArgTys;
2342 QualType argT = Context->getObjCIdType();
2343 assert(!argT.isNull() && "Can't find 'id' type");
2344 ArgTys.push_back(argT);
2345 argT = Context->getObjCSelType();
2346 assert(!argT.isNull() && "Can't find 'SEL' type");
2347 ArgTys.push_back(argT);
2348 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2349 &ArgTys[0], ArgTys.size(),
2350 true /*isVariadic*/);
2351 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2352 SourceLocation(),
2353 SourceLocation(),
2354 msgSendIdent, msgSendType, 0,
2355 SC_Extern,
2356 SC_None, false);
2357}
2358
2359// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2360void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2361 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2362 SmallVector<QualType, 16> ArgTys;
2363 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2364 SourceLocation(), SourceLocation(),
2365 &Context->Idents.get("objc_super"));
2366 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2367 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2368 ArgTys.push_back(argT);
2369 argT = Context->getObjCSelType();
2370 assert(!argT.isNull() && "Can't find 'SEL' type");
2371 ArgTys.push_back(argT);
2372 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2373 &ArgTys[0], ArgTys.size(),
2374 true /*isVariadic*/);
2375 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2376 SourceLocation(),
2377 SourceLocation(),
2378 msgSendIdent, msgSendType, 0,
2379 SC_Extern,
2380 SC_None, false);
2381}
2382
2383// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2384void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2385 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2386 SmallVector<QualType, 16> ArgTys;
2387 QualType argT = Context->getObjCIdType();
2388 assert(!argT.isNull() && "Can't find 'id' type");
2389 ArgTys.push_back(argT);
2390 argT = Context->getObjCSelType();
2391 assert(!argT.isNull() && "Can't find 'SEL' type");
2392 ArgTys.push_back(argT);
2393 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2394 &ArgTys[0], ArgTys.size(),
2395 true /*isVariadic*/);
2396 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2397 SourceLocation(),
2398 SourceLocation(),
2399 msgSendIdent, msgSendType, 0,
2400 SC_Extern,
2401 SC_None, false);
2402}
2403
2404// SynthMsgSendSuperStretFunctionDecl -
2405// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2406void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2407 IdentifierInfo *msgSendIdent =
2408 &Context->Idents.get("objc_msgSendSuper_stret");
2409 SmallVector<QualType, 16> ArgTys;
2410 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2411 SourceLocation(), SourceLocation(),
2412 &Context->Idents.get("objc_super"));
2413 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2414 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2415 ArgTys.push_back(argT);
2416 argT = Context->getObjCSelType();
2417 assert(!argT.isNull() && "Can't find 'SEL' type");
2418 ArgTys.push_back(argT);
2419 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2420 &ArgTys[0], ArgTys.size(),
2421 true /*isVariadic*/);
2422 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2423 SourceLocation(),
2424 SourceLocation(),
2425 msgSendIdent, msgSendType, 0,
2426 SC_Extern,
2427 SC_None, false);
2428}
2429
2430// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2431void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2432 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2433 SmallVector<QualType, 16> ArgTys;
2434 QualType argT = Context->getObjCIdType();
2435 assert(!argT.isNull() && "Can't find 'id' type");
2436 ArgTys.push_back(argT);
2437 argT = Context->getObjCSelType();
2438 assert(!argT.isNull() && "Can't find 'SEL' type");
2439 ArgTys.push_back(argT);
2440 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2441 &ArgTys[0], ArgTys.size(),
2442 true /*isVariadic*/);
2443 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2444 SourceLocation(),
2445 SourceLocation(),
2446 msgSendIdent, msgSendType, 0,
2447 SC_Extern,
2448 SC_None, false);
2449}
2450
2451// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2452void RewriteModernObjC::SynthGetClassFunctionDecl() {
2453 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2454 SmallVector<QualType, 16> ArgTys;
2455 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2456 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2457 &ArgTys[0], ArgTys.size());
2458 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2459 SourceLocation(),
2460 SourceLocation(),
2461 getClassIdent, getClassType, 0,
2462 SC_Extern,
2463 SC_None, false);
2464}
2465
2466// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2467void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2468 IdentifierInfo *getSuperClassIdent =
2469 &Context->Idents.get("class_getSuperclass");
2470 SmallVector<QualType, 16> ArgTys;
2471 ArgTys.push_back(Context->getObjCClassType());
2472 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2473 &ArgTys[0], ArgTys.size());
2474 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2475 SourceLocation(),
2476 SourceLocation(),
2477 getSuperClassIdent,
2478 getClassType, 0,
2479 SC_Extern,
2480 SC_None,
2481 false);
2482}
2483
2484// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2485void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2486 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2487 SmallVector<QualType, 16> ArgTys;
2488 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2489 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2490 &ArgTys[0], ArgTys.size());
2491 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2492 SourceLocation(),
2493 SourceLocation(),
2494 getClassIdent, getClassType, 0,
2495 SC_Extern,
2496 SC_None, false);
2497}
2498
2499Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2500 QualType strType = getConstantStringStructType();
2501
2502 std::string S = "__NSConstantStringImpl_";
2503
2504 std::string tmpName = InFileName;
2505 unsigned i;
2506 for (i=0; i < tmpName.length(); i++) {
2507 char c = tmpName.at(i);
2508 // replace any non alphanumeric characters with '_'.
2509 if (!isalpha(c) && (c < '0' || c > '9'))
2510 tmpName[i] = '_';
2511 }
2512 S += tmpName;
2513 S += "_";
2514 S += utostr(NumObjCStringLiterals++);
2515
2516 Preamble += "static __NSConstantStringImpl " + S;
2517 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2518 Preamble += "0x000007c8,"; // utf8_str
2519 // The pretty printer for StringLiteral handles escape characters properly.
2520 std::string prettyBufS;
2521 llvm::raw_string_ostream prettyBuf(prettyBufS);
2522 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2523 PrintingPolicy(LangOpts));
2524 Preamble += prettyBuf.str();
2525 Preamble += ",";
2526 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2527
2528 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2529 SourceLocation(), &Context->Idents.get(S),
2530 strType, 0, SC_Static, SC_None);
2531 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2532 SourceLocation());
2533 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2534 Context->getPointerType(DRE->getType()),
2535 VK_RValue, OK_Ordinary,
2536 SourceLocation());
2537 // cast to NSConstantString *
2538 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2539 CK_CPointerToObjCPointerCast, Unop);
2540 ReplaceStmt(Exp, cast);
2541 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2542 return cast;
2543}
2544
2545// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2546QualType RewriteModernObjC::getSuperStructType() {
2547 if (!SuperStructDecl) {
2548 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2549 SourceLocation(), SourceLocation(),
2550 &Context->Idents.get("objc_super"));
2551 QualType FieldTypes[2];
2552
2553 // struct objc_object *receiver;
2554 FieldTypes[0] = Context->getObjCIdType();
2555 // struct objc_class *super;
2556 FieldTypes[1] = Context->getObjCClassType();
2557
2558 // Create fields
2559 for (unsigned i = 0; i < 2; ++i) {
2560 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2561 SourceLocation(),
2562 SourceLocation(), 0,
2563 FieldTypes[i], 0,
2564 /*BitWidth=*/0,
2565 /*Mutable=*/false,
2566 /*HasInit=*/false));
2567 }
2568
2569 SuperStructDecl->completeDefinition();
2570 }
2571 return Context->getTagDeclType(SuperStructDecl);
2572}
2573
2574QualType RewriteModernObjC::getConstantStringStructType() {
2575 if (!ConstantStringDecl) {
2576 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2577 SourceLocation(), SourceLocation(),
2578 &Context->Idents.get("__NSConstantStringImpl"));
2579 QualType FieldTypes[4];
2580
2581 // struct objc_object *receiver;
2582 FieldTypes[0] = Context->getObjCIdType();
2583 // int flags;
2584 FieldTypes[1] = Context->IntTy;
2585 // char *str;
2586 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2587 // long length;
2588 FieldTypes[3] = Context->LongTy;
2589
2590 // Create fields
2591 for (unsigned i = 0; i < 4; ++i) {
2592 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2593 ConstantStringDecl,
2594 SourceLocation(),
2595 SourceLocation(), 0,
2596 FieldTypes[i], 0,
2597 /*BitWidth=*/0,
2598 /*Mutable=*/true,
2599 /*HasInit=*/false));
2600 }
2601
2602 ConstantStringDecl->completeDefinition();
2603 }
2604 return Context->getTagDeclType(ConstantStringDecl);
2605}
2606
2607Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2608 SourceLocation StartLoc,
2609 SourceLocation EndLoc) {
2610 if (!SelGetUidFunctionDecl)
2611 SynthSelGetUidFunctionDecl();
2612 if (!MsgSendFunctionDecl)
2613 SynthMsgSendFunctionDecl();
2614 if (!MsgSendSuperFunctionDecl)
2615 SynthMsgSendSuperFunctionDecl();
2616 if (!MsgSendStretFunctionDecl)
2617 SynthMsgSendStretFunctionDecl();
2618 if (!MsgSendSuperStretFunctionDecl)
2619 SynthMsgSendSuperStretFunctionDecl();
2620 if (!MsgSendFpretFunctionDecl)
2621 SynthMsgSendFpretFunctionDecl();
2622 if (!GetClassFunctionDecl)
2623 SynthGetClassFunctionDecl();
2624 if (!GetSuperClassFunctionDecl)
2625 SynthGetSuperClassFunctionDecl();
2626 if (!GetMetaClassFunctionDecl)
2627 SynthGetMetaClassFunctionDecl();
2628
2629 // default to objc_msgSend().
2630 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2631 // May need to use objc_msgSend_stret() as well.
2632 FunctionDecl *MsgSendStretFlavor = 0;
2633 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2634 QualType resultType = mDecl->getResultType();
2635 if (resultType->isRecordType())
2636 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2637 else if (resultType->isRealFloatingType())
2638 MsgSendFlavor = MsgSendFpretFunctionDecl;
2639 }
2640
2641 // Synthesize a call to objc_msgSend().
2642 SmallVector<Expr*, 8> MsgExprs;
2643 switch (Exp->getReceiverKind()) {
2644 case ObjCMessageExpr::SuperClass: {
2645 MsgSendFlavor = MsgSendSuperFunctionDecl;
2646 if (MsgSendStretFlavor)
2647 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2648 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2649
2650 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2651
2652 SmallVector<Expr*, 4> InitExprs;
2653
2654 // set the receiver to self, the first argument to all methods.
2655 InitExprs.push_back(
2656 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2657 CK_BitCast,
2658 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2659 Context->getObjCIdType(),
2660 VK_RValue,
2661 SourceLocation()))
2662 ); // set the 'receiver'.
2663
2664 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2665 SmallVector<Expr*, 8> ClsExprs;
2666 QualType argType = Context->getPointerType(Context->CharTy);
2667 ClsExprs.push_back(StringLiteral::Create(*Context,
2668 ClassDecl->getIdentifier()->getName(),
2669 StringLiteral::Ascii, false,
2670 argType, SourceLocation()));
2671 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2672 &ClsExprs[0],
2673 ClsExprs.size(),
2674 StartLoc,
2675 EndLoc);
2676 // (Class)objc_getClass("CurrentClass")
2677 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2678 Context->getObjCClassType(),
2679 CK_BitCast, Cls);
2680 ClsExprs.clear();
2681 ClsExprs.push_back(ArgExpr);
2682 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2683 &ClsExprs[0], ClsExprs.size(),
2684 StartLoc, EndLoc);
2685
2686 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2687 // To turn off a warning, type-cast to 'id'
2688 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2689 NoTypeInfoCStyleCastExpr(Context,
2690 Context->getObjCIdType(),
2691 CK_BitCast, Cls));
2692 // struct objc_super
2693 QualType superType = getSuperStructType();
2694 Expr *SuperRep;
2695
2696 if (LangOpts.MicrosoftExt) {
2697 SynthSuperContructorFunctionDecl();
2698 // Simulate a contructor call...
2699 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2700 superType, VK_LValue,
2701 SourceLocation());
2702 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2703 InitExprs.size(),
2704 superType, VK_LValue,
2705 SourceLocation());
2706 // The code for super is a little tricky to prevent collision with
2707 // the structure definition in the header. The rewriter has it's own
2708 // internal definition (__rw_objc_super) that is uses. This is why
2709 // we need the cast below. For example:
2710 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2711 //
2712 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2713 Context->getPointerType(SuperRep->getType()),
2714 VK_RValue, OK_Ordinary,
2715 SourceLocation());
2716 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2717 Context->getPointerType(superType),
2718 CK_BitCast, SuperRep);
2719 } else {
2720 // (struct objc_super) { <exprs from above> }
2721 InitListExpr *ILE =
2722 new (Context) InitListExpr(*Context, SourceLocation(),
2723 &InitExprs[0], InitExprs.size(),
2724 SourceLocation());
2725 TypeSourceInfo *superTInfo
2726 = Context->getTrivialTypeSourceInfo(superType);
2727 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2728 superType, VK_LValue,
2729 ILE, false);
2730 // struct objc_super *
2731 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2732 Context->getPointerType(SuperRep->getType()),
2733 VK_RValue, OK_Ordinary,
2734 SourceLocation());
2735 }
2736 MsgExprs.push_back(SuperRep);
2737 break;
2738 }
2739
2740 case ObjCMessageExpr::Class: {
2741 SmallVector<Expr*, 8> ClsExprs;
2742 QualType argType = Context->getPointerType(Context->CharTy);
2743 ObjCInterfaceDecl *Class
2744 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2745 IdentifierInfo *clsName = Class->getIdentifier();
2746 ClsExprs.push_back(StringLiteral::Create(*Context,
2747 clsName->getName(),
2748 StringLiteral::Ascii, false,
2749 argType, SourceLocation()));
2750 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2751 &ClsExprs[0],
2752 ClsExprs.size(),
2753 StartLoc, EndLoc);
2754 MsgExprs.push_back(Cls);
2755 break;
2756 }
2757
2758 case ObjCMessageExpr::SuperInstance:{
2759 MsgSendFlavor = MsgSendSuperFunctionDecl;
2760 if (MsgSendStretFlavor)
2761 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2762 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2763 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2764 SmallVector<Expr*, 4> InitExprs;
2765
2766 InitExprs.push_back(
2767 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2768 CK_BitCast,
2769 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2770 Context->getObjCIdType(),
2771 VK_RValue, SourceLocation()))
2772 ); // set the 'receiver'.
2773
2774 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2775 SmallVector<Expr*, 8> ClsExprs;
2776 QualType argType = Context->getPointerType(Context->CharTy);
2777 ClsExprs.push_back(StringLiteral::Create(*Context,
2778 ClassDecl->getIdentifier()->getName(),
2779 StringLiteral::Ascii, false, argType,
2780 SourceLocation()));
2781 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2782 &ClsExprs[0],
2783 ClsExprs.size(),
2784 StartLoc, EndLoc);
2785 // (Class)objc_getClass("CurrentClass")
2786 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2787 Context->getObjCClassType(),
2788 CK_BitCast, Cls);
2789 ClsExprs.clear();
2790 ClsExprs.push_back(ArgExpr);
2791 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2792 &ClsExprs[0], ClsExprs.size(),
2793 StartLoc, EndLoc);
2794
2795 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2796 // To turn off a warning, type-cast to 'id'
2797 InitExprs.push_back(
2798 // set 'super class', using class_getSuperclass().
2799 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2800 CK_BitCast, Cls));
2801 // struct objc_super
2802 QualType superType = getSuperStructType();
2803 Expr *SuperRep;
2804
2805 if (LangOpts.MicrosoftExt) {
2806 SynthSuperContructorFunctionDecl();
2807 // Simulate a contructor call...
2808 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2809 superType, VK_LValue,
2810 SourceLocation());
2811 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2812 InitExprs.size(),
2813 superType, VK_LValue, SourceLocation());
2814 // The code for super is a little tricky to prevent collision with
2815 // the structure definition in the header. The rewriter has it's own
2816 // internal definition (__rw_objc_super) that is uses. This is why
2817 // we need the cast below. For example:
2818 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2819 //
2820 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2821 Context->getPointerType(SuperRep->getType()),
2822 VK_RValue, OK_Ordinary,
2823 SourceLocation());
2824 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2825 Context->getPointerType(superType),
2826 CK_BitCast, SuperRep);
2827 } else {
2828 // (struct objc_super) { <exprs from above> }
2829 InitListExpr *ILE =
2830 new (Context) InitListExpr(*Context, SourceLocation(),
2831 &InitExprs[0], InitExprs.size(),
2832 SourceLocation());
2833 TypeSourceInfo *superTInfo
2834 = Context->getTrivialTypeSourceInfo(superType);
2835 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2836 superType, VK_RValue, ILE,
2837 false);
2838 }
2839 MsgExprs.push_back(SuperRep);
2840 break;
2841 }
2842
2843 case ObjCMessageExpr::Instance: {
2844 // Remove all type-casts because it may contain objc-style types; e.g.
2845 // Foo<Proto> *.
2846 Expr *recExpr = Exp->getInstanceReceiver();
2847 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2848 recExpr = CE->getSubExpr();
2849 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2850 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2851 ? CK_BlockPointerToObjCPointerCast
2852 : CK_CPointerToObjCPointerCast;
2853
2854 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2855 CK, recExpr);
2856 MsgExprs.push_back(recExpr);
2857 break;
2858 }
2859 }
2860
2861 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2862 SmallVector<Expr*, 8> SelExprs;
2863 QualType argType = Context->getPointerType(Context->CharTy);
2864 SelExprs.push_back(StringLiteral::Create(*Context,
2865 Exp->getSelector().getAsString(),
2866 StringLiteral::Ascii, false,
2867 argType, SourceLocation()));
2868 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2869 &SelExprs[0], SelExprs.size(),
2870 StartLoc,
2871 EndLoc);
2872 MsgExprs.push_back(SelExp);
2873
2874 // Now push any user supplied arguments.
2875 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2876 Expr *userExpr = Exp->getArg(i);
2877 // Make all implicit casts explicit...ICE comes in handy:-)
2878 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2879 // Reuse the ICE type, it is exactly what the doctor ordered.
2880 QualType type = ICE->getType();
2881 if (needToScanForQualifiers(type))
2882 type = Context->getObjCIdType();
2883 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2884 (void)convertBlockPointerToFunctionPointer(type);
2885 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2886 CastKind CK;
2887 if (SubExpr->getType()->isIntegralType(*Context) &&
2888 type->isBooleanType()) {
2889 CK = CK_IntegralToBoolean;
2890 } else if (type->isObjCObjectPointerType()) {
2891 if (SubExpr->getType()->isBlockPointerType()) {
2892 CK = CK_BlockPointerToObjCPointerCast;
2893 } else if (SubExpr->getType()->isPointerType()) {
2894 CK = CK_CPointerToObjCPointerCast;
2895 } else {
2896 CK = CK_BitCast;
2897 }
2898 } else {
2899 CK = CK_BitCast;
2900 }
2901
2902 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2903 }
2904 // Make id<P...> cast into an 'id' cast.
2905 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2906 if (CE->getType()->isObjCQualifiedIdType()) {
2907 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2908 userExpr = CE->getSubExpr();
2909 CastKind CK;
2910 if (userExpr->getType()->isIntegralType(*Context)) {
2911 CK = CK_IntegralToPointer;
2912 } else if (userExpr->getType()->isBlockPointerType()) {
2913 CK = CK_BlockPointerToObjCPointerCast;
2914 } else if (userExpr->getType()->isPointerType()) {
2915 CK = CK_CPointerToObjCPointerCast;
2916 } else {
2917 CK = CK_BitCast;
2918 }
2919 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2920 CK, userExpr);
2921 }
2922 }
2923 MsgExprs.push_back(userExpr);
2924 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2925 // out the argument in the original expression (since we aren't deleting
2926 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2927 //Exp->setArg(i, 0);
2928 }
2929 // Generate the funky cast.
2930 CastExpr *cast;
2931 SmallVector<QualType, 8> ArgTypes;
2932 QualType returnType;
2933
2934 // Push 'id' and 'SEL', the 2 implicit arguments.
2935 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2936 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2937 else
2938 ArgTypes.push_back(Context->getObjCIdType());
2939 ArgTypes.push_back(Context->getObjCSelType());
2940 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2941 // Push any user argument types.
2942 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2943 E = OMD->param_end(); PI != E; ++PI) {
2944 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2945 ? Context->getObjCIdType()
2946 : (*PI)->getType();
2947 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2948 (void)convertBlockPointerToFunctionPointer(t);
2949 ArgTypes.push_back(t);
2950 }
2951 returnType = Exp->getType();
2952 convertToUnqualifiedObjCType(returnType);
2953 (void)convertBlockPointerToFunctionPointer(returnType);
2954 } else {
2955 returnType = Context->getObjCIdType();
2956 }
2957 // Get the type, we will need to reference it in a couple spots.
2958 QualType msgSendType = MsgSendFlavor->getType();
2959
2960 // Create a reference to the objc_msgSend() declaration.
2961 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
2962 VK_LValue, SourceLocation());
2963
2964 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2965 // If we don't do this cast, we get the following bizarre warning/note:
2966 // xx.m:13: warning: function called through a non-compatible type
2967 // xx.m:13: note: if this code is reached, the program will abort
2968 cast = NoTypeInfoCStyleCastExpr(Context,
2969 Context->getPointerType(Context->VoidTy),
2970 CK_BitCast, DRE);
2971
2972 // Now do the "normal" pointer to function cast.
2973 QualType castType =
2974 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2975 // If we don't have a method decl, force a variadic cast.
2976 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2977 castType = Context->getPointerType(castType);
2978 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2979 cast);
2980
2981 // Don't forget the parens to enforce the proper binding.
2982 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2983
2984 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2985 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2986 MsgExprs.size(),
2987 FT->getResultType(), VK_RValue,
2988 EndLoc);
2989 Stmt *ReplacingStmt = CE;
2990 if (MsgSendStretFlavor) {
2991 // We have the method which returns a struct/union. Must also generate
2992 // call to objc_msgSend_stret and hang both varieties on a conditional
2993 // expression which dictate which one to envoke depending on size of
2994 // method's return type.
2995
2996 // Create a reference to the objc_msgSend_stret() declaration.
2997 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
2998 VK_LValue, SourceLocation());
2999 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3000 cast = NoTypeInfoCStyleCastExpr(Context,
3001 Context->getPointerType(Context->VoidTy),
3002 CK_BitCast, STDRE);
3003 // Now do the "normal" pointer to function cast.
3004 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3005 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3006 castType = Context->getPointerType(castType);
3007 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3008 cast);
3009
3010 // Don't forget the parens to enforce the proper binding.
3011 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3012
3013 FT = msgSendType->getAs<FunctionType>();
3014 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3015 MsgExprs.size(),
3016 FT->getResultType(), VK_RValue,
3017 SourceLocation());
3018
3019 // Build sizeof(returnType)
3020 UnaryExprOrTypeTraitExpr *sizeofExpr =
3021 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3022 Context->getTrivialTypeSourceInfo(returnType),
3023 Context->getSizeType(), SourceLocation(),
3024 SourceLocation());
3025 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3026 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3027 // For X86 it is more complicated and some kind of target specific routine
3028 // is needed to decide what to do.
3029 unsigned IntSize =
3030 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3031 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3032 llvm::APInt(IntSize, 8),
3033 Context->IntTy,
3034 SourceLocation());
3035 BinaryOperator *lessThanExpr =
3036 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3037 VK_RValue, OK_Ordinary, SourceLocation());
3038 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3039 ConditionalOperator *CondExpr =
3040 new (Context) ConditionalOperator(lessThanExpr,
3041 SourceLocation(), CE,
3042 SourceLocation(), STCE,
3043 returnType, VK_RValue, OK_Ordinary);
3044 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3045 CondExpr);
3046 }
3047 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3048 return ReplacingStmt;
3049}
3050
3051Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3052 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3053 Exp->getLocEnd());
3054
3055 // Now do the actual rewrite.
3056 ReplaceStmt(Exp, ReplacingStmt);
3057
3058 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3059 return ReplacingStmt;
3060}
3061
3062// typedef struct objc_object Protocol;
3063QualType RewriteModernObjC::getProtocolType() {
3064 if (!ProtocolTypeDecl) {
3065 TypeSourceInfo *TInfo
3066 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3067 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3068 SourceLocation(), SourceLocation(),
3069 &Context->Idents.get("Protocol"),
3070 TInfo);
3071 }
3072 return Context->getTypeDeclType(ProtocolTypeDecl);
3073}
3074
3075/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3076/// a synthesized/forward data reference (to the protocol's metadata).
3077/// The forward references (and metadata) are generated in
3078/// RewriteModernObjC::HandleTranslationUnit().
3079Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3080 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3081 IdentifierInfo *ID = &Context->Idents.get(Name);
3082 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3083 SourceLocation(), ID, getProtocolType(), 0,
3084 SC_Extern, SC_None);
3085 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3086 SourceLocation());
3087 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3088 Context->getPointerType(DRE->getType()),
3089 VK_RValue, OK_Ordinary, SourceLocation());
3090 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3091 CK_BitCast,
3092 DerefExpr);
3093 ReplaceStmt(Exp, castExpr);
3094 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3095 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3096 return castExpr;
3097
3098}
3099
3100bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3101 const char *endBuf) {
3102 while (startBuf < endBuf) {
3103 if (*startBuf == '#') {
3104 // Skip whitespace.
3105 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3106 ;
3107 if (!strncmp(startBuf, "if", strlen("if")) ||
3108 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3109 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3110 !strncmp(startBuf, "define", strlen("define")) ||
3111 !strncmp(startBuf, "undef", strlen("undef")) ||
3112 !strncmp(startBuf, "else", strlen("else")) ||
3113 !strncmp(startBuf, "elif", strlen("elif")) ||
3114 !strncmp(startBuf, "endif", strlen("endif")) ||
3115 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3116 !strncmp(startBuf, "include", strlen("include")) ||
3117 !strncmp(startBuf, "import", strlen("import")) ||
3118 !strncmp(startBuf, "include_next", strlen("include_next")))
3119 return true;
3120 }
3121 startBuf++;
3122 }
3123 return false;
3124}
3125
3126/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3127/// an objective-c class with ivars.
3128void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3129 std::string &Result) {
3130 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3131 assert(CDecl->getName() != "" &&
3132 "Name missing in SynthesizeObjCInternalStruct");
3133 // Do not synthesize more than once.
3134 if (ObjCSynthesizedStructs.count(CDecl))
3135 return;
3136 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3137 int NumIvars = CDecl->ivar_size();
3138 SourceLocation LocStart = CDecl->getLocStart();
3139 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3140
3141 const char *startBuf = SM->getCharacterData(LocStart);
3142 const char *endBuf = SM->getCharacterData(LocEnd);
3143
3144 // If no ivars and no root or if its root, directly or indirectly,
3145 // have no ivars (thus not synthesized) then no need to synthesize this class.
3146 if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
3147 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3148 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3149 ReplaceText(LocStart, endBuf-startBuf, Result);
3150 return;
3151 }
3152
3153 // FIXME: This has potential of causing problem. If
3154 // SynthesizeObjCInternalStruct is ever called recursively.
3155 Result += "\nstruct ";
3156 Result += CDecl->getNameAsString();
3157 if (LangOpts.MicrosoftExt)
3158 Result += "_IMPL";
3159
3160 if (NumIvars > 0) {
3161 const char *cursor = strchr(startBuf, '{');
3162 assert((cursor && endBuf)
3163 && "SynthesizeObjCInternalStruct - malformed @interface");
3164 // If the buffer contains preprocessor directives, we do more fine-grained
3165 // rewrites. This is intended to fix code that looks like (which occurs in
3166 // NSURL.h, for example):
3167 //
3168 // #ifdef XYZ
3169 // @interface Foo : NSObject
3170 // #else
3171 // @interface FooBar : NSObject
3172 // #endif
3173 // {
3174 // int i;
3175 // }
3176 // @end
3177 //
3178 // This clause is segregated to avoid breaking the common case.
3179 if (BufferContainsPPDirectives(startBuf, cursor)) {
3180 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
3181 CDecl->getAtStartLoc();
3182 const char *endHeader = SM->getCharacterData(L);
3183 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
3184
3185 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3186 // advance to the end of the referenced protocols.
3187 while (endHeader < cursor && *endHeader != '>') endHeader++;
3188 endHeader++;
3189 }
3190 // rewrite the original header
3191 ReplaceText(LocStart, endHeader-startBuf, Result);
3192 } else {
3193 // rewrite the original header *without* disturbing the '{'
3194 ReplaceText(LocStart, cursor-startBuf, Result);
3195 }
3196 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3197 Result = "\n struct ";
3198 Result += RCDecl->getNameAsString();
3199 Result += "_IMPL ";
3200 Result += RCDecl->getNameAsString();
3201 Result += "_IVARS;\n";
3202
3203 // insert the super class structure definition.
3204 SourceLocation OnePastCurly =
3205 LocStart.getLocWithOffset(cursor-startBuf+1);
3206 InsertText(OnePastCurly, Result);
3207 }
3208 cursor++; // past '{'
3209
3210 // Now comment out any visibility specifiers.
3211 while (cursor < endBuf) {
3212 if (*cursor == '@') {
3213 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3214 // Skip whitespace.
3215 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3216 /*scan*/;
3217
3218 // FIXME: presence of @public, etc. inside comment results in
3219 // this transformation as well, which is still correct c-code.
3220 if (!strncmp(cursor, "public", strlen("public")) ||
3221 !strncmp(cursor, "private", strlen("private")) ||
3222 !strncmp(cursor, "package", strlen("package")) ||
3223 !strncmp(cursor, "protected", strlen("protected")))
3224 InsertText(atLoc, "// ");
3225 }
3226 // FIXME: If there are cases where '<' is used in ivar declaration part
3227 // of user code, then scan the ivar list and use needToScanForQualifiers
3228 // for type checking.
3229 else if (*cursor == '<') {
3230 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3231 InsertText(atLoc, "/* ");
3232 cursor = strchr(cursor, '>');
3233 cursor++;
3234 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3235 InsertText(atLoc, " */");
3236 } else if (*cursor == '^') { // rewrite block specifier.
3237 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
3238 ReplaceText(caretLoc, 1, "*");
3239 }
3240 cursor++;
3241 }
3242 // Don't forget to add a ';'!!
3243 InsertText(LocEnd.getLocWithOffset(1), ";");
3244 } else { // we don't have any instance variables - insert super struct.
3245 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3246 Result += " {\n struct ";
3247 Result += RCDecl->getNameAsString();
3248 Result += "_IMPL ";
3249 Result += RCDecl->getNameAsString();
3250 Result += "_IVARS;\n};\n";
3251 ReplaceText(LocStart, endBuf-startBuf, Result);
3252 }
3253 // Mark this struct as having been generated.
3254 if (!ObjCSynthesizedStructs.insert(CDecl))
3255 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
3256}
3257
3258//===----------------------------------------------------------------------===//
3259// Meta Data Emission
3260//===----------------------------------------------------------------------===//
3261
3262
3263/// RewriteImplementations - This routine rewrites all method implementations
3264/// and emits meta-data.
3265
3266void RewriteModernObjC::RewriteImplementations() {
3267 int ClsDefCount = ClassImplementation.size();
3268 int CatDefCount = CategoryImplementation.size();
3269
3270 // Rewrite implemented methods
3271 for (int i = 0; i < ClsDefCount; i++)
3272 RewriteImplementationDecl(ClassImplementation[i]);
3273
3274 for (int i = 0; i < CatDefCount; i++)
3275 RewriteImplementationDecl(CategoryImplementation[i]);
3276}
3277
3278void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3279 const std::string &Name,
3280 ValueDecl *VD, bool def) {
3281 assert(BlockByRefDeclNo.count(VD) &&
3282 "RewriteByRefString: ByRef decl missing");
3283 if (def)
3284 ResultStr += "struct ";
3285 ResultStr += "__Block_byref_" + Name +
3286 "_" + utostr(BlockByRefDeclNo[VD]) ;
3287}
3288
3289static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3290 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3291 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3292 return false;
3293}
3294
3295std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3296 StringRef funcName,
3297 std::string Tag) {
3298 const FunctionType *AFT = CE->getFunctionType();
3299 QualType RT = AFT->getResultType();
3300 std::string StructRef = "struct " + Tag;
3301 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3302 funcName.str() + "_" + "block_func_" + utostr(i);
3303
3304 BlockDecl *BD = CE->getBlockDecl();
3305
3306 if (isa<FunctionNoProtoType>(AFT)) {
3307 // No user-supplied arguments. Still need to pass in a pointer to the
3308 // block (to reference imported block decl refs).
3309 S += "(" + StructRef + " *__cself)";
3310 } else if (BD->param_empty()) {
3311 S += "(" + StructRef + " *__cself)";
3312 } else {
3313 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3314 assert(FT && "SynthesizeBlockFunc: No function proto");
3315 S += '(';
3316 // first add the implicit argument.
3317 S += StructRef + " *__cself, ";
3318 std::string ParamStr;
3319 for (BlockDecl::param_iterator AI = BD->param_begin(),
3320 E = BD->param_end(); AI != E; ++AI) {
3321 if (AI != BD->param_begin()) S += ", ";
3322 ParamStr = (*AI)->getNameAsString();
3323 QualType QT = (*AI)->getType();
3324 if (convertBlockPointerToFunctionPointer(QT))
3325 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3326 else
3327 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3328 S += ParamStr;
3329 }
3330 if (FT->isVariadic()) {
3331 if (!BD->param_empty()) S += ", ";
3332 S += "...";
3333 }
3334 S += ')';
3335 }
3336 S += " {\n";
3337
3338 // Create local declarations to avoid rewriting all closure decl ref exprs.
3339 // First, emit a declaration for all "by ref" decls.
3340 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3341 E = BlockByRefDecls.end(); I != E; ++I) {
3342 S += " ";
3343 std::string Name = (*I)->getNameAsString();
3344 std::string TypeString;
3345 RewriteByRefString(TypeString, Name, (*I));
3346 TypeString += " *";
3347 Name = TypeString + Name;
3348 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3349 }
3350 // Next, emit a declaration for all "by copy" declarations.
3351 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3352 E = BlockByCopyDecls.end(); I != E; ++I) {
3353 S += " ";
3354 // Handle nested closure invocation. For example:
3355 //
3356 // void (^myImportedClosure)(void);
3357 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3358 //
3359 // void (^anotherClosure)(void);
3360 // anotherClosure = ^(void) {
3361 // myImportedClosure(); // import and invoke the closure
3362 // };
3363 //
3364 if (isTopLevelBlockPointerType((*I)->getType())) {
3365 RewriteBlockPointerTypeVariable(S, (*I));
3366 S += " = (";
3367 RewriteBlockPointerType(S, (*I)->getType());
3368 S += ")";
3369 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3370 }
3371 else {
3372 std::string Name = (*I)->getNameAsString();
3373 QualType QT = (*I)->getType();
3374 if (HasLocalVariableExternalStorage(*I))
3375 QT = Context->getPointerType(QT);
3376 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3377 S += Name + " = __cself->" +
3378 (*I)->getNameAsString() + "; // bound by copy\n";
3379 }
3380 }
3381 std::string RewrittenStr = RewrittenBlockExprs[CE];
3382 const char *cstr = RewrittenStr.c_str();
3383 while (*cstr++ != '{') ;
3384 S += cstr;
3385 S += "\n";
3386 return S;
3387}
3388
3389std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3390 StringRef funcName,
3391 std::string Tag) {
3392 std::string StructRef = "struct " + Tag;
3393 std::string S = "static void __";
3394
3395 S += funcName;
3396 S += "_block_copy_" + utostr(i);
3397 S += "(" + StructRef;
3398 S += "*dst, " + StructRef;
3399 S += "*src) {";
3400 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3401 E = ImportedBlockDecls.end(); I != E; ++I) {
3402 ValueDecl *VD = (*I);
3403 S += "_Block_object_assign((void*)&dst->";
3404 S += (*I)->getNameAsString();
3405 S += ", (void*)src->";
3406 S += (*I)->getNameAsString();
3407 if (BlockByRefDeclsPtrSet.count((*I)))
3408 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3409 else if (VD->getType()->isBlockPointerType())
3410 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3411 else
3412 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3413 }
3414 S += "}\n";
3415
3416 S += "\nstatic void __";
3417 S += funcName;
3418 S += "_block_dispose_" + utostr(i);
3419 S += "(" + StructRef;
3420 S += "*src) {";
3421 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3422 E = ImportedBlockDecls.end(); I != E; ++I) {
3423 ValueDecl *VD = (*I);
3424 S += "_Block_object_dispose((void*)src->";
3425 S += (*I)->getNameAsString();
3426 if (BlockByRefDeclsPtrSet.count((*I)))
3427 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3428 else if (VD->getType()->isBlockPointerType())
3429 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3430 else
3431 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3432 }
3433 S += "}\n";
3434 return S;
3435}
3436
3437std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3438 std::string Desc) {
3439 std::string S = "\nstruct " + Tag;
3440 std::string Constructor = " " + Tag;
3441
3442 S += " {\n struct __block_impl impl;\n";
3443 S += " struct " + Desc;
3444 S += "* Desc;\n";
3445
3446 Constructor += "(void *fp, "; // Invoke function pointer.
3447 Constructor += "struct " + Desc; // Descriptor pointer.
3448 Constructor += " *desc";
3449
3450 if (BlockDeclRefs.size()) {
3451 // Output all "by copy" declarations.
3452 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3453 E = BlockByCopyDecls.end(); I != E; ++I) {
3454 S += " ";
3455 std::string FieldName = (*I)->getNameAsString();
3456 std::string ArgName = "_" + FieldName;
3457 // Handle nested closure invocation. For example:
3458 //
3459 // void (^myImportedBlock)(void);
3460 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3461 //
3462 // void (^anotherBlock)(void);
3463 // anotherBlock = ^(void) {
3464 // myImportedBlock(); // import and invoke the closure
3465 // };
3466 //
3467 if (isTopLevelBlockPointerType((*I)->getType())) {
3468 S += "struct __block_impl *";
3469 Constructor += ", void *" + ArgName;
3470 } else {
3471 QualType QT = (*I)->getType();
3472 if (HasLocalVariableExternalStorage(*I))
3473 QT = Context->getPointerType(QT);
3474 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3475 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3476 Constructor += ", " + ArgName;
3477 }
3478 S += FieldName + ";\n";
3479 }
3480 // Output all "by ref" declarations.
3481 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3482 E = BlockByRefDecls.end(); I != E; ++I) {
3483 S += " ";
3484 std::string FieldName = (*I)->getNameAsString();
3485 std::string ArgName = "_" + FieldName;
3486 {
3487 std::string TypeString;
3488 RewriteByRefString(TypeString, FieldName, (*I));
3489 TypeString += " *";
3490 FieldName = TypeString + FieldName;
3491 ArgName = TypeString + ArgName;
3492 Constructor += ", " + ArgName;
3493 }
3494 S += FieldName + "; // by ref\n";
3495 }
3496 // Finish writing the constructor.
3497 Constructor += ", int flags=0)";
3498 // Initialize all "by copy" arguments.
3499 bool firsTime = true;
3500 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3501 E = BlockByCopyDecls.end(); I != E; ++I) {
3502 std::string Name = (*I)->getNameAsString();
3503 if (firsTime) {
3504 Constructor += " : ";
3505 firsTime = false;
3506 }
3507 else
3508 Constructor += ", ";
3509 if (isTopLevelBlockPointerType((*I)->getType()))
3510 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3511 else
3512 Constructor += Name + "(_" + Name + ")";
3513 }
3514 // Initialize all "by ref" arguments.
3515 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3516 E = BlockByRefDecls.end(); I != E; ++I) {
3517 std::string Name = (*I)->getNameAsString();
3518 if (firsTime) {
3519 Constructor += " : ";
3520 firsTime = false;
3521 }
3522 else
3523 Constructor += ", ";
3524 Constructor += Name + "(_" + Name + "->__forwarding)";
3525 }
3526
3527 Constructor += " {\n";
3528 if (GlobalVarDecl)
3529 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3530 else
3531 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3532 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3533
3534 Constructor += " Desc = desc;\n";
3535 } else {
3536 // Finish writing the constructor.
3537 Constructor += ", int flags=0) {\n";
3538 if (GlobalVarDecl)
3539 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3540 else
3541 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3542 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3543 Constructor += " Desc = desc;\n";
3544 }
3545 Constructor += " ";
3546 Constructor += "}\n";
3547 S += Constructor;
3548 S += "};\n";
3549 return S;
3550}
3551
3552std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3553 std::string ImplTag, int i,
3554 StringRef FunName,
3555 unsigned hasCopy) {
3556 std::string S = "\nstatic struct " + DescTag;
3557
3558 S += " {\n unsigned long reserved;\n";
3559 S += " unsigned long Block_size;\n";
3560 if (hasCopy) {
3561 S += " void (*copy)(struct ";
3562 S += ImplTag; S += "*, struct ";
3563 S += ImplTag; S += "*);\n";
3564
3565 S += " void (*dispose)(struct ";
3566 S += ImplTag; S += "*);\n";
3567 }
3568 S += "} ";
3569
3570 S += DescTag + "_DATA = { 0, sizeof(struct ";
3571 S += ImplTag + ")";
3572 if (hasCopy) {
3573 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3574 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3575 }
3576 S += "};\n";
3577 return S;
3578}
3579
3580void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3581 StringRef FunName) {
3582 // Insert declaration for the function in which block literal is used.
3583 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3584 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3585 bool RewriteSC = (GlobalVarDecl &&
3586 !Blocks.empty() &&
3587 GlobalVarDecl->getStorageClass() == SC_Static &&
3588 GlobalVarDecl->getType().getCVRQualifiers());
3589 if (RewriteSC) {
3590 std::string SC(" void __");
3591 SC += GlobalVarDecl->getNameAsString();
3592 SC += "() {}";
3593 InsertText(FunLocStart, SC);
3594 }
3595
3596 // Insert closures that were part of the function.
3597 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3598 CollectBlockDeclRefInfo(Blocks[i]);
3599 // Need to copy-in the inner copied-in variables not actually used in this
3600 // block.
3601 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3602 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3603 ValueDecl *VD = Exp->getDecl();
3604 BlockDeclRefs.push_back(Exp);
3605 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3606 BlockByCopyDeclsPtrSet.insert(VD);
3607 BlockByCopyDecls.push_back(VD);
3608 }
3609 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3610 BlockByRefDeclsPtrSet.insert(VD);
3611 BlockByRefDecls.push_back(VD);
3612 }
3613 // imported objects in the inner blocks not used in the outer
3614 // blocks must be copied/disposed in the outer block as well.
3615 if (Exp->isByRef() ||
3616 VD->getType()->isObjCObjectPointerType() ||
3617 VD->getType()->isBlockPointerType())
3618 ImportedBlockDecls.insert(VD);
3619 }
3620
3621 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3622 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3623
3624 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3625
3626 InsertText(FunLocStart, CI);
3627
3628 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3629
3630 InsertText(FunLocStart, CF);
3631
3632 if (ImportedBlockDecls.size()) {
3633 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3634 InsertText(FunLocStart, HF);
3635 }
3636 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3637 ImportedBlockDecls.size() > 0);
3638 InsertText(FunLocStart, BD);
3639
3640 BlockDeclRefs.clear();
3641 BlockByRefDecls.clear();
3642 BlockByRefDeclsPtrSet.clear();
3643 BlockByCopyDecls.clear();
3644 BlockByCopyDeclsPtrSet.clear();
3645 ImportedBlockDecls.clear();
3646 }
3647 if (RewriteSC) {
3648 // Must insert any 'const/volatile/static here. Since it has been
3649 // removed as result of rewriting of block literals.
3650 std::string SC;
3651 if (GlobalVarDecl->getStorageClass() == SC_Static)
3652 SC = "static ";
3653 if (GlobalVarDecl->getType().isConstQualified())
3654 SC += "const ";
3655 if (GlobalVarDecl->getType().isVolatileQualified())
3656 SC += "volatile ";
3657 if (GlobalVarDecl->getType().isRestrictQualified())
3658 SC += "restrict ";
3659 InsertText(FunLocStart, SC);
3660 }
3661
3662 Blocks.clear();
3663 InnerDeclRefsCount.clear();
3664 InnerDeclRefs.clear();
3665 RewrittenBlockExprs.clear();
3666}
3667
3668void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3669 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3670 StringRef FuncName = FD->getName();
3671
3672 SynthesizeBlockLiterals(FunLocStart, FuncName);
3673}
3674
3675static void BuildUniqueMethodName(std::string &Name,
3676 ObjCMethodDecl *MD) {
3677 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3678 Name = IFace->getName();
3679 Name += "__" + MD->getSelector().getAsString();
3680 // Convert colons to underscores.
3681 std::string::size_type loc = 0;
3682 while ((loc = Name.find(":", loc)) != std::string::npos)
3683 Name.replace(loc, 1, "_");
3684}
3685
3686void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3687 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3688 //SourceLocation FunLocStart = MD->getLocStart();
3689 SourceLocation FunLocStart = MD->getLocStart();
3690 std::string FuncName;
3691 BuildUniqueMethodName(FuncName, MD);
3692 SynthesizeBlockLiterals(FunLocStart, FuncName);
3693}
3694
3695void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3696 for (Stmt::child_range CI = S->children(); CI; ++CI)
3697 if (*CI) {
3698 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3699 GetBlockDeclRefExprs(CBE->getBody());
3700 else
3701 GetBlockDeclRefExprs(*CI);
3702 }
3703 // Handle specific things.
3704 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3705 // FIXME: Handle enums.
3706 if (!isa<FunctionDecl>(CDRE->getDecl()))
3707 BlockDeclRefs.push_back(CDRE);
3708 }
3709 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3710 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3711 BlockDeclRefExpr *BDRE =
3712 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3713 DRE->getType(),
3714 VK_LValue, DRE->getLocation(), false);
3715 BlockDeclRefs.push_back(BDRE);
3716 }
3717
3718 return;
3719}
3720
3721void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3722 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
3723 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3724 for (Stmt::child_range CI = S->children(); CI; ++CI)
3725 if (*CI) {
3726 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3727 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3728 GetInnerBlockDeclRefExprs(CBE->getBody(),
3729 InnerBlockDeclRefs,
3730 InnerContexts);
3731 }
3732 else
3733 GetInnerBlockDeclRefExprs(*CI,
3734 InnerBlockDeclRefs,
3735 InnerContexts);
3736
3737 }
3738 // Handle specific things.
3739 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3740 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
3741 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
3742 InnerBlockDeclRefs.push_back(CDRE);
3743 }
3744 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3745 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3746 if (Var->isFunctionOrMethodVarDecl())
3747 ImportedLocalExternalDecls.insert(Var);
3748 }
3749
3750 return;
3751}
3752
3753/// convertFunctionTypeOfBlocks - This routine converts a function type
3754/// whose result type may be a block pointer or whose argument type(s)
3755/// might be block pointers to an equivalent function type replacing
3756/// all block pointers to function pointers.
3757QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3758 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3759 // FTP will be null for closures that don't take arguments.
3760 // Generate a funky cast.
3761 SmallVector<QualType, 8> ArgTypes;
3762 QualType Res = FT->getResultType();
3763 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
3764
3765 if (FTP) {
3766 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3767 E = FTP->arg_type_end(); I && (I != E); ++I) {
3768 QualType t = *I;
3769 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3770 if (convertBlockPointerToFunctionPointer(t))
3771 HasBlockType = true;
3772 ArgTypes.push_back(t);
3773 }
3774 }
3775 QualType FuncType;
3776 // FIXME. Does this work if block takes no argument but has a return type
3777 // which is of block type?
3778 if (HasBlockType)
3779 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3780 else FuncType = QualType(FT, 0);
3781 return FuncType;
3782}
3783
3784Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3785 // Navigate to relevant type information.
3786 const BlockPointerType *CPT = 0;
3787
3788 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3789 CPT = DRE->getType()->getAs<BlockPointerType>();
3790 } else if (const BlockDeclRefExpr *CDRE =
3791 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
3792 CPT = CDRE->getType()->getAs<BlockPointerType>();
3793 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3794 CPT = MExpr->getType()->getAs<BlockPointerType>();
3795 }
3796 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3797 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3798 }
3799 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3800 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3801 else if (const ConditionalOperator *CEXPR =
3802 dyn_cast<ConditionalOperator>(BlockExp)) {
3803 Expr *LHSExp = CEXPR->getLHS();
3804 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3805 Expr *RHSExp = CEXPR->getRHS();
3806 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3807 Expr *CONDExp = CEXPR->getCond();
3808 ConditionalOperator *CondExpr =
3809 new (Context) ConditionalOperator(CONDExp,
3810 SourceLocation(), cast<Expr>(LHSStmt),
3811 SourceLocation(), cast<Expr>(RHSStmt),
3812 Exp->getType(), VK_RValue, OK_Ordinary);
3813 return CondExpr;
3814 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3815 CPT = IRE->getType()->getAs<BlockPointerType>();
3816 } else if (const PseudoObjectExpr *POE
3817 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3818 CPT = POE->getType()->castAs<BlockPointerType>();
3819 } else {
3820 assert(1 && "RewriteBlockClass: Bad type");
3821 }
3822 assert(CPT && "RewriteBlockClass: Bad type");
3823 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3824 assert(FT && "RewriteBlockClass: Bad type");
3825 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3826 // FTP will be null for closures that don't take arguments.
3827
3828 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3829 SourceLocation(), SourceLocation(),
3830 &Context->Idents.get("__block_impl"));
3831 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3832
3833 // Generate a funky cast.
3834 SmallVector<QualType, 8> ArgTypes;
3835
3836 // Push the block argument type.
3837 ArgTypes.push_back(PtrBlock);
3838 if (FTP) {
3839 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3840 E = FTP->arg_type_end(); I && (I != E); ++I) {
3841 QualType t = *I;
3842 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3843 if (!convertBlockPointerToFunctionPointer(t))
3844 convertToUnqualifiedObjCType(t);
3845 ArgTypes.push_back(t);
3846 }
3847 }
3848 // Now do the pointer to function cast.
3849 QualType PtrToFuncCastType
3850 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3851
3852 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3853
3854 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3855 CK_BitCast,
3856 const_cast<Expr*>(BlockExp));
3857 // Don't forget the parens to enforce the proper binding.
3858 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3859 BlkCast);
3860 //PE->dump();
3861
3862 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3863 SourceLocation(),
3864 &Context->Idents.get("FuncPtr"),
3865 Context->VoidPtrTy, 0,
3866 /*BitWidth=*/0, /*Mutable=*/true,
3867 /*HasInit=*/false);
3868 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3869 FD->getType(), VK_LValue,
3870 OK_Ordinary);
3871
3872
3873 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3874 CK_BitCast, ME);
3875 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3876
3877 SmallVector<Expr*, 8> BlkExprs;
3878 // Add the implicit argument.
3879 BlkExprs.push_back(BlkCast);
3880 // Add the user arguments.
3881 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3882 E = Exp->arg_end(); I != E; ++I) {
3883 BlkExprs.push_back(*I);
3884 }
3885 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3886 BlkExprs.size(),
3887 Exp->getType(), VK_RValue,
3888 SourceLocation());
3889 return CE;
3890}
3891
3892// We need to return the rewritten expression to handle cases where the
3893// BlockDeclRefExpr is embedded in another expression being rewritten.
3894// For example:
3895//
3896// int main() {
3897// __block Foo *f;
3898// __block int i;
3899//
3900// void (^myblock)() = ^() {
3901// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3902// i = 77;
3903// };
3904//}
3905Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
3906 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3907 // for each DeclRefExp where BYREFVAR is name of the variable.
3908 ValueDecl *VD;
3909 bool isArrow = true;
3910 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3911 VD = BDRE->getDecl();
3912 else {
3913 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
3914 isArrow = false;
3915 }
3916
3917 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3918 SourceLocation(),
3919 &Context->Idents.get("__forwarding"),
3920 Context->VoidPtrTy, 0,
3921 /*BitWidth=*/0, /*Mutable=*/true,
3922 /*HasInit=*/false);
3923 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3924 FD, SourceLocation(),
3925 FD->getType(), VK_LValue,
3926 OK_Ordinary);
3927
3928 StringRef Name = VD->getName();
3929 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3930 &Context->Idents.get(Name),
3931 Context->VoidPtrTy, 0,
3932 /*BitWidth=*/0, /*Mutable=*/true,
3933 /*HasInit=*/false);
3934 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3935 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3936
3937
3938
3939 // Need parens to enforce precedence.
3940 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3941 DeclRefExp->getExprLoc(),
3942 ME);
3943 ReplaceStmt(DeclRefExp, PE);
3944 return PE;
3945}
3946
3947// Rewrites the imported local variable V with external storage
3948// (static, extern, etc.) as *V
3949//
3950Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3951 ValueDecl *VD = DRE->getDecl();
3952 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3953 if (!ImportedLocalExternalDecls.count(Var))
3954 return DRE;
3955 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3956 VK_LValue, OK_Ordinary,
3957 DRE->getLocation());
3958 // Need parens to enforce precedence.
3959 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3960 Exp);
3961 ReplaceStmt(DRE, PE);
3962 return PE;
3963}
3964
3965void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3966 SourceLocation LocStart = CE->getLParenLoc();
3967 SourceLocation LocEnd = CE->getRParenLoc();
3968
3969 // Need to avoid trying to rewrite synthesized casts.
3970 if (LocStart.isInvalid())
3971 return;
3972 // Need to avoid trying to rewrite casts contained in macros.
3973 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3974 return;
3975
3976 const char *startBuf = SM->getCharacterData(LocStart);
3977 const char *endBuf = SM->getCharacterData(LocEnd);
3978 QualType QT = CE->getType();
3979 const Type* TypePtr = QT->getAs<Type>();
3980 if (isa<TypeOfExprType>(TypePtr)) {
3981 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3982 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3983 std::string TypeAsString = "(";
3984 RewriteBlockPointerType(TypeAsString, QT);
3985 TypeAsString += ")";
3986 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3987 return;
3988 }
3989 // advance the location to startArgList.
3990 const char *argPtr = startBuf;
3991
3992 while (*argPtr++ && (argPtr < endBuf)) {
3993 switch (*argPtr) {
3994 case '^':
3995 // Replace the '^' with '*'.
3996 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3997 ReplaceText(LocStart, 1, "*");
3998 break;
3999 }
4000 }
4001 return;
4002}
4003
4004void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4005 SourceLocation DeclLoc = FD->getLocation();
4006 unsigned parenCount = 0;
4007
4008 // We have 1 or more arguments that have closure pointers.
4009 const char *startBuf = SM->getCharacterData(DeclLoc);
4010 const char *startArgList = strchr(startBuf, '(');
4011
4012 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4013
4014 parenCount++;
4015 // advance the location to startArgList.
4016 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4017 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4018
4019 const char *argPtr = startArgList;
4020
4021 while (*argPtr++ && parenCount) {
4022 switch (*argPtr) {
4023 case '^':
4024 // Replace the '^' with '*'.
4025 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4026 ReplaceText(DeclLoc, 1, "*");
4027 break;
4028 case '(':
4029 parenCount++;
4030 break;
4031 case ')':
4032 parenCount--;
4033 break;
4034 }
4035 }
4036 return;
4037}
4038
4039bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4040 const FunctionProtoType *FTP;
4041 const PointerType *PT = QT->getAs<PointerType>();
4042 if (PT) {
4043 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4044 } else {
4045 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4046 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4047 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4048 }
4049 if (FTP) {
4050 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4051 E = FTP->arg_type_end(); I != E; ++I)
4052 if (isTopLevelBlockPointerType(*I))
4053 return true;
4054 }
4055 return false;
4056}
4057
4058bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4059 const FunctionProtoType *FTP;
4060 const PointerType *PT = QT->getAs<PointerType>();
4061 if (PT) {
4062 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4063 } else {
4064 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4065 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4066 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4067 }
4068 if (FTP) {
4069 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4070 E = FTP->arg_type_end(); I != E; ++I) {
4071 if ((*I)->isObjCQualifiedIdType())
4072 return true;
4073 if ((*I)->isObjCObjectPointerType() &&
4074 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4075 return true;
4076 }
4077
4078 }
4079 return false;
4080}
4081
4082void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4083 const char *&RParen) {
4084 const char *argPtr = strchr(Name, '(');
4085 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4086
4087 LParen = argPtr; // output the start.
4088 argPtr++; // skip past the left paren.
4089 unsigned parenCount = 1;
4090
4091 while (*argPtr && parenCount) {
4092 switch (*argPtr) {
4093 case '(': parenCount++; break;
4094 case ')': parenCount--; break;
4095 default: break;
4096 }
4097 if (parenCount) argPtr++;
4098 }
4099 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4100 RParen = argPtr; // output the end
4101}
4102
4103void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4104 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4105 RewriteBlockPointerFunctionArgs(FD);
4106 return;
4107 }
4108 // Handle Variables and Typedefs.
4109 SourceLocation DeclLoc = ND->getLocation();
4110 QualType DeclT;
4111 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4112 DeclT = VD->getType();
4113 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4114 DeclT = TDD->getUnderlyingType();
4115 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4116 DeclT = FD->getType();
4117 else
4118 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4119
4120 const char *startBuf = SM->getCharacterData(DeclLoc);
4121 const char *endBuf = startBuf;
4122 // scan backward (from the decl location) for the end of the previous decl.
4123 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4124 startBuf--;
4125 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4126 std::string buf;
4127 unsigned OrigLength=0;
4128 // *startBuf != '^' if we are dealing with a pointer to function that
4129 // may take block argument types (which will be handled below).
4130 if (*startBuf == '^') {
4131 // Replace the '^' with '*', computing a negative offset.
4132 buf = '*';
4133 startBuf++;
4134 OrigLength++;
4135 }
4136 while (*startBuf != ')') {
4137 buf += *startBuf;
4138 startBuf++;
4139 OrigLength++;
4140 }
4141 buf += ')';
4142 OrigLength++;
4143
4144 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4145 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4146 // Replace the '^' with '*' for arguments.
4147 // Replace id<P> with id/*<>*/
4148 DeclLoc = ND->getLocation();
4149 startBuf = SM->getCharacterData(DeclLoc);
4150 const char *argListBegin, *argListEnd;
4151 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4152 while (argListBegin < argListEnd) {
4153 if (*argListBegin == '^')
4154 buf += '*';
4155 else if (*argListBegin == '<') {
4156 buf += "/*";
4157 buf += *argListBegin++;
4158 OrigLength++;;
4159 while (*argListBegin != '>') {
4160 buf += *argListBegin++;
4161 OrigLength++;
4162 }
4163 buf += *argListBegin;
4164 buf += "*/";
4165 }
4166 else
4167 buf += *argListBegin;
4168 argListBegin++;
4169 OrigLength++;
4170 }
4171 buf += ')';
4172 OrigLength++;
4173 }
4174 ReplaceText(Start, OrigLength, buf);
4175
4176 return;
4177}
4178
4179
4180/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4181/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4182/// struct Block_byref_id_object *src) {
4183/// _Block_object_assign (&_dest->object, _src->object,
4184/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4185/// [|BLOCK_FIELD_IS_WEAK]) // object
4186/// _Block_object_assign(&_dest->object, _src->object,
4187/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4188/// [|BLOCK_FIELD_IS_WEAK]) // block
4189/// }
4190/// And:
4191/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4192/// _Block_object_dispose(_src->object,
4193/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4194/// [|BLOCK_FIELD_IS_WEAK]) // object
4195/// _Block_object_dispose(_src->object,
4196/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4197/// [|BLOCK_FIELD_IS_WEAK]) // block
4198/// }
4199
4200std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4201 int flag) {
4202 std::string S;
4203 if (CopyDestroyCache.count(flag))
4204 return S;
4205 CopyDestroyCache.insert(flag);
4206 S = "static void __Block_byref_id_object_copy_";
4207 S += utostr(flag);
4208 S += "(void *dst, void *src) {\n";
4209
4210 // offset into the object pointer is computed as:
4211 // void * + void* + int + int + void* + void *
4212 unsigned IntSize =
4213 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4214 unsigned VoidPtrSize =
4215 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4216
4217 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4218 S += " _Block_object_assign((char*)dst + ";
4219 S += utostr(offset);
4220 S += ", *(void * *) ((char*)src + ";
4221 S += utostr(offset);
4222 S += "), ";
4223 S += utostr(flag);
4224 S += ");\n}\n";
4225
4226 S += "static void __Block_byref_id_object_dispose_";
4227 S += utostr(flag);
4228 S += "(void *src) {\n";
4229 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4230 S += utostr(offset);
4231 S += "), ";
4232 S += utostr(flag);
4233 S += ");\n}\n";
4234 return S;
4235}
4236
4237/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4238/// the declaration into:
4239/// struct __Block_byref_ND {
4240/// void *__isa; // NULL for everything except __weak pointers
4241/// struct __Block_byref_ND *__forwarding;
4242/// int32_t __flags;
4243/// int32_t __size;
4244/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4245/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4246/// typex ND;
4247/// };
4248///
4249/// It then replaces declaration of ND variable with:
4250/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4251/// __size=sizeof(struct __Block_byref_ND),
4252/// ND=initializer-if-any};
4253///
4254///
4255void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4256 // Insert declaration for the function in which block literal is
4257 // used.
4258 if (CurFunctionDeclToDeclareForBlock)
4259 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4260 int flag = 0;
4261 int isa = 0;
4262 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4263 if (DeclLoc.isInvalid())
4264 // If type location is missing, it is because of missing type (a warning).
4265 // Use variable's location which is good for this case.
4266 DeclLoc = ND->getLocation();
4267 const char *startBuf = SM->getCharacterData(DeclLoc);
4268 SourceLocation X = ND->getLocEnd();
4269 X = SM->getExpansionLoc(X);
4270 const char *endBuf = SM->getCharacterData(X);
4271 std::string Name(ND->getNameAsString());
4272 std::string ByrefType;
4273 RewriteByRefString(ByrefType, Name, ND, true);
4274 ByrefType += " {\n";
4275 ByrefType += " void *__isa;\n";
4276 RewriteByRefString(ByrefType, Name, ND);
4277 ByrefType += " *__forwarding;\n";
4278 ByrefType += " int __flags;\n";
4279 ByrefType += " int __size;\n";
4280 // Add void *__Block_byref_id_object_copy;
4281 // void *__Block_byref_id_object_dispose; if needed.
4282 QualType Ty = ND->getType();
4283 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4284 if (HasCopyAndDispose) {
4285 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4286 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4287 }
4288
4289 QualType T = Ty;
4290 (void)convertBlockPointerToFunctionPointer(T);
4291 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4292
4293 ByrefType += " " + Name + ";\n";
4294 ByrefType += "};\n";
4295 // Insert this type in global scope. It is needed by helper function.
4296 SourceLocation FunLocStart;
4297 if (CurFunctionDef)
4298 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4299 else {
4300 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4301 FunLocStart = CurMethodDef->getLocStart();
4302 }
4303 InsertText(FunLocStart, ByrefType);
4304 if (Ty.isObjCGCWeak()) {
4305 flag |= BLOCK_FIELD_IS_WEAK;
4306 isa = 1;
4307 }
4308
4309 if (HasCopyAndDispose) {
4310 flag = BLOCK_BYREF_CALLER;
4311 QualType Ty = ND->getType();
4312 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4313 if (Ty->isBlockPointerType())
4314 flag |= BLOCK_FIELD_IS_BLOCK;
4315 else
4316 flag |= BLOCK_FIELD_IS_OBJECT;
4317 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4318 if (!HF.empty())
4319 InsertText(FunLocStart, HF);
4320 }
4321
4322 // struct __Block_byref_ND ND =
4323 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4324 // initializer-if-any};
4325 bool hasInit = (ND->getInit() != 0);
4326 unsigned flags = 0;
4327 if (HasCopyAndDispose)
4328 flags |= BLOCK_HAS_COPY_DISPOSE;
4329 Name = ND->getNameAsString();
4330 ByrefType.clear();
4331 RewriteByRefString(ByrefType, Name, ND);
4332 std::string ForwardingCastType("(");
4333 ForwardingCastType += ByrefType + " *)";
4334 if (!hasInit) {
4335 ByrefType += " " + Name + " = {(void*)";
4336 ByrefType += utostr(isa);
4337 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4338 ByrefType += utostr(flags);
4339 ByrefType += ", ";
4340 ByrefType += "sizeof(";
4341 RewriteByRefString(ByrefType, Name, ND);
4342 ByrefType += ")";
4343 if (HasCopyAndDispose) {
4344 ByrefType += ", __Block_byref_id_object_copy_";
4345 ByrefType += utostr(flag);
4346 ByrefType += ", __Block_byref_id_object_dispose_";
4347 ByrefType += utostr(flag);
4348 }
4349 ByrefType += "};\n";
4350 unsigned nameSize = Name.size();
4351 // for block or function pointer declaration. Name is aleady
4352 // part of the declaration.
4353 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4354 nameSize = 1;
4355 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4356 }
4357 else {
4358 SourceLocation startLoc;
4359 Expr *E = ND->getInit();
4360 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4361 startLoc = ECE->getLParenLoc();
4362 else
4363 startLoc = E->getLocStart();
4364 startLoc = SM->getExpansionLoc(startLoc);
4365 endBuf = SM->getCharacterData(startLoc);
4366 ByrefType += " " + Name;
4367 ByrefType += " = {(void*)";
4368 ByrefType += utostr(isa);
4369 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4370 ByrefType += utostr(flags);
4371 ByrefType += ", ";
4372 ByrefType += "sizeof(";
4373 RewriteByRefString(ByrefType, Name, ND);
4374 ByrefType += "), ";
4375 if (HasCopyAndDispose) {
4376 ByrefType += "__Block_byref_id_object_copy_";
4377 ByrefType += utostr(flag);
4378 ByrefType += ", __Block_byref_id_object_dispose_";
4379 ByrefType += utostr(flag);
4380 ByrefType += ", ";
4381 }
4382 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4383
4384 // Complete the newly synthesized compound expression by inserting a right
4385 // curly brace before the end of the declaration.
4386 // FIXME: This approach avoids rewriting the initializer expression. It
4387 // also assumes there is only one declarator. For example, the following
4388 // isn't currently supported by this routine (in general):
4389 //
4390 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4391 //
4392 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4393 const char *semiBuf = strchr(startInitializerBuf, ';');
4394 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4395 SourceLocation semiLoc =
4396 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4397
4398 InsertText(semiLoc, "}");
4399 }
4400 return;
4401}
4402
4403void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4404 // Add initializers for any closure decl refs.
4405 GetBlockDeclRefExprs(Exp->getBody());
4406 if (BlockDeclRefs.size()) {
4407 // Unique all "by copy" declarations.
4408 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4409 if (!BlockDeclRefs[i]->isByRef()) {
4410 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4411 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4412 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4413 }
4414 }
4415 // Unique all "by ref" declarations.
4416 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4417 if (BlockDeclRefs[i]->isByRef()) {
4418 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4419 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4420 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4421 }
4422 }
4423 // Find any imported blocks...they will need special attention.
4424 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4425 if (BlockDeclRefs[i]->isByRef() ||
4426 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4427 BlockDeclRefs[i]->getType()->isBlockPointerType())
4428 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4429 }
4430}
4431
4432FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4433 IdentifierInfo *ID = &Context->Idents.get(name);
4434 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4435 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4436 SourceLocation(), ID, FType, 0, SC_Extern,
4437 SC_None, false, false);
4438}
4439
4440Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
4441 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
4442 const BlockDecl *block = Exp->getBlockDecl();
4443 Blocks.push_back(Exp);
4444
4445 CollectBlockDeclRefInfo(Exp);
4446
4447 // Add inner imported variables now used in current block.
4448 int countOfInnerDecls = 0;
4449 if (!InnerBlockDeclRefs.empty()) {
4450 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4451 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4452 ValueDecl *VD = Exp->getDecl();
4453 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4454 // We need to save the copied-in variables in nested
4455 // blocks because it is needed at the end for some of the API generations.
4456 // See SynthesizeBlockLiterals routine.
4457 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4458 BlockDeclRefs.push_back(Exp);
4459 BlockByCopyDeclsPtrSet.insert(VD);
4460 BlockByCopyDecls.push_back(VD);
4461 }
4462 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4463 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4464 BlockDeclRefs.push_back(Exp);
4465 BlockByRefDeclsPtrSet.insert(VD);
4466 BlockByRefDecls.push_back(VD);
4467 }
4468 }
4469 // Find any imported blocks...they will need special attention.
4470 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4471 if (InnerBlockDeclRefs[i]->isByRef() ||
4472 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4473 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4474 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4475 }
4476 InnerDeclRefsCount.push_back(countOfInnerDecls);
4477
4478 std::string FuncName;
4479
4480 if (CurFunctionDef)
4481 FuncName = CurFunctionDef->getNameAsString();
4482 else if (CurMethodDef)
4483 BuildUniqueMethodName(FuncName, CurMethodDef);
4484 else if (GlobalVarDecl)
4485 FuncName = std::string(GlobalVarDecl->getNameAsString());
4486
4487 std::string BlockNumber = utostr(Blocks.size()-1);
4488
4489 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4490 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4491
4492 // Get a pointer to the function type so we can cast appropriately.
4493 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4494 QualType FType = Context->getPointerType(BFT);
4495
4496 FunctionDecl *FD;
4497 Expr *NewRep;
4498
4499 // Simulate a contructor call...
4500 FD = SynthBlockInitFunctionDecl(Tag);
4501 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4502 SourceLocation());
4503
4504 SmallVector<Expr*, 4> InitExprs;
4505
4506 // Initialize the block function.
4507 FD = SynthBlockInitFunctionDecl(Func);
4508 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4509 SourceLocation());
4510 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4511 CK_BitCast, Arg);
4512 InitExprs.push_back(castExpr);
4513
4514 // Initialize the block descriptor.
4515 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4516
4517 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4518 SourceLocation(), SourceLocation(),
4519 &Context->Idents.get(DescData.c_str()),
4520 Context->VoidPtrTy, 0,
4521 SC_Static, SC_None);
4522 UnaryOperator *DescRefExpr =
4523 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4524 Context->VoidPtrTy,
4525 VK_LValue,
4526 SourceLocation()),
4527 UO_AddrOf,
4528 Context->getPointerType(Context->VoidPtrTy),
4529 VK_RValue, OK_Ordinary,
4530 SourceLocation());
4531 InitExprs.push_back(DescRefExpr);
4532
4533 // Add initializers for any closure decl refs.
4534 if (BlockDeclRefs.size()) {
4535 Expr *Exp;
4536 // Output all "by copy" declarations.
4537 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4538 E = BlockByCopyDecls.end(); I != E; ++I) {
4539 if (isObjCType((*I)->getType())) {
4540 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4541 FD = SynthBlockInitFunctionDecl((*I)->getName());
4542 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4543 SourceLocation());
4544 if (HasLocalVariableExternalStorage(*I)) {
4545 QualType QT = (*I)->getType();
4546 QT = Context->getPointerType(QT);
4547 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4548 OK_Ordinary, SourceLocation());
4549 }
4550 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4551 FD = SynthBlockInitFunctionDecl((*I)->getName());
4552 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4553 SourceLocation());
4554 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4555 CK_BitCast, Arg);
4556 } else {
4557 FD = SynthBlockInitFunctionDecl((*I)->getName());
4558 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4559 SourceLocation());
4560 if (HasLocalVariableExternalStorage(*I)) {
4561 QualType QT = (*I)->getType();
4562 QT = Context->getPointerType(QT);
4563 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4564 OK_Ordinary, SourceLocation());
4565 }
4566
4567 }
4568 InitExprs.push_back(Exp);
4569 }
4570 // Output all "by ref" declarations.
4571 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4572 E = BlockByRefDecls.end(); I != E; ++I) {
4573 ValueDecl *ND = (*I);
4574 std::string Name(ND->getNameAsString());
4575 std::string RecName;
4576 RewriteByRefString(RecName, Name, ND, true);
4577 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4578 + sizeof("struct"));
4579 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4580 SourceLocation(), SourceLocation(),
4581 II);
4582 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4583 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4584
4585 FD = SynthBlockInitFunctionDecl((*I)->getName());
4586 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4587 SourceLocation());
4588 bool isNestedCapturedVar = false;
4589 if (block)
4590 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4591 ce = block->capture_end(); ci != ce; ++ci) {
4592 const VarDecl *variable = ci->getVariable();
4593 if (variable == ND && ci->isNested()) {
4594 assert (ci->isByRef() &&
4595 "SynthBlockInitExpr - captured block variable is not byref");
4596 isNestedCapturedVar = true;
4597 break;
4598 }
4599 }
4600 // captured nested byref variable has its address passed. Do not take
4601 // its address again.
4602 if (!isNestedCapturedVar)
4603 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4604 Context->getPointerType(Exp->getType()),
4605 VK_RValue, OK_Ordinary, SourceLocation());
4606 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4607 InitExprs.push_back(Exp);
4608 }
4609 }
4610 if (ImportedBlockDecls.size()) {
4611 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4612 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4613 unsigned IntSize =
4614 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4615 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4616 Context->IntTy, SourceLocation());
4617 InitExprs.push_back(FlagExp);
4618 }
4619 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4620 FType, VK_LValue, SourceLocation());
4621 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4622 Context->getPointerType(NewRep->getType()),
4623 VK_RValue, OK_Ordinary, SourceLocation());
4624 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4625 NewRep);
4626 BlockDeclRefs.clear();
4627 BlockByRefDecls.clear();
4628 BlockByRefDeclsPtrSet.clear();
4629 BlockByCopyDecls.clear();
4630 BlockByCopyDeclsPtrSet.clear();
4631 ImportedBlockDecls.clear();
4632 return NewRep;
4633}
4634
4635bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4636 if (const ObjCForCollectionStmt * CS =
4637 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4638 return CS->getElement() == DS;
4639 return false;
4640}
4641
4642//===----------------------------------------------------------------------===//
4643// Function Body / Expression rewriting
4644//===----------------------------------------------------------------------===//
4645
4646Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4647 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4648 isa<DoStmt>(S) || isa<ForStmt>(S))
4649 Stmts.push_back(S);
4650 else if (isa<ObjCForCollectionStmt>(S)) {
4651 Stmts.push_back(S);
4652 ObjCBcLabelNo.push_back(++BcLabelCount);
4653 }
4654
4655 // Pseudo-object operations and ivar references need special
4656 // treatment because we're going to recursively rewrite them.
4657 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4658 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4659 return RewritePropertyOrImplicitSetter(PseudoOp);
4660 } else {
4661 return RewritePropertyOrImplicitGetter(PseudoOp);
4662 }
4663 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4664 return RewriteObjCIvarRefExpr(IvarRefExpr);
4665 }
4666
4667 SourceRange OrigStmtRange = S->getSourceRange();
4668
4669 // Perform a bottom up rewrite of all children.
4670 for (Stmt::child_range CI = S->children(); CI; ++CI)
4671 if (*CI) {
4672 Stmt *childStmt = (*CI);
4673 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4674 if (newStmt) {
4675 *CI = newStmt;
4676 }
4677 }
4678
4679 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4680 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
4681 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4682 InnerContexts.insert(BE->getBlockDecl());
4683 ImportedLocalExternalDecls.clear();
4684 GetInnerBlockDeclRefExprs(BE->getBody(),
4685 InnerBlockDeclRefs, InnerContexts);
4686 // Rewrite the block body in place.
4687 Stmt *SaveCurrentBody = CurrentBody;
4688 CurrentBody = BE->getBody();
4689 PropParentMap = 0;
4690 // block literal on rhs of a property-dot-sytax assignment
4691 // must be replaced by its synthesize ast so getRewrittenText
4692 // works as expected. In this case, what actually ends up on RHS
4693 // is the blockTranscribed which is the helper function for the
4694 // block literal; as in: self.c = ^() {[ace ARR];};
4695 bool saveDisableReplaceStmt = DisableReplaceStmt;
4696 DisableReplaceStmt = false;
4697 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4698 DisableReplaceStmt = saveDisableReplaceStmt;
4699 CurrentBody = SaveCurrentBody;
4700 PropParentMap = 0;
4701 ImportedLocalExternalDecls.clear();
4702 // Now we snarf the rewritten text and stash it away for later use.
4703 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4704 RewrittenBlockExprs[BE] = Str;
4705
4706 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4707
4708 //blockTranscribed->dump();
4709 ReplaceStmt(S, blockTranscribed);
4710 return blockTranscribed;
4711 }
4712 // Handle specific things.
4713 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4714 return RewriteAtEncode(AtEncode);
4715
4716 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4717 return RewriteAtSelector(AtSelector);
4718
4719 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4720 return RewriteObjCStringLiteral(AtString);
4721
4722 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4723#if 0
4724 // Before we rewrite it, put the original message expression in a comment.
4725 SourceLocation startLoc = MessExpr->getLocStart();
4726 SourceLocation endLoc = MessExpr->getLocEnd();
4727
4728 const char *startBuf = SM->getCharacterData(startLoc);
4729 const char *endBuf = SM->getCharacterData(endLoc);
4730
4731 std::string messString;
4732 messString += "// ";
4733 messString.append(startBuf, endBuf-startBuf+1);
4734 messString += "\n";
4735
4736 // FIXME: Missing definition of
4737 // InsertText(clang::SourceLocation, char const*, unsigned int).
4738 // InsertText(startLoc, messString.c_str(), messString.size());
4739 // Tried this, but it didn't work either...
4740 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4741#endif
4742 return RewriteMessageExpr(MessExpr);
4743 }
4744
4745 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4746 return RewriteObjCTryStmt(StmtTry);
4747
4748 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4749 return RewriteObjCSynchronizedStmt(StmtTry);
4750
4751 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4752 return RewriteObjCThrowStmt(StmtThrow);
4753
4754 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4755 return RewriteObjCProtocolExpr(ProtocolExp);
4756
4757 if (ObjCForCollectionStmt *StmtForCollection =
4758 dyn_cast<ObjCForCollectionStmt>(S))
4759 return RewriteObjCForCollectionStmt(StmtForCollection,
4760 OrigStmtRange.getEnd());
4761 if (BreakStmt *StmtBreakStmt =
4762 dyn_cast<BreakStmt>(S))
4763 return RewriteBreakStmt(StmtBreakStmt);
4764 if (ContinueStmt *StmtContinueStmt =
4765 dyn_cast<ContinueStmt>(S))
4766 return RewriteContinueStmt(StmtContinueStmt);
4767
4768 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4769 // and cast exprs.
4770 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4771 // FIXME: What we're doing here is modifying the type-specifier that
4772 // precedes the first Decl. In the future the DeclGroup should have
4773 // a separate type-specifier that we can rewrite.
4774 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4775 // the context of an ObjCForCollectionStmt. For example:
4776 // NSArray *someArray;
4777 // for (id <FooProtocol> index in someArray) ;
4778 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4779 // and it depends on the original text locations/positions.
4780 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4781 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4782
4783 // Blocks rewrite rules.
4784 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4785 DI != DE; ++DI) {
4786 Decl *SD = *DI;
4787 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4788 if (isTopLevelBlockPointerType(ND->getType()))
4789 RewriteBlockPointerDecl(ND);
4790 else if (ND->getType()->isFunctionPointerType())
4791 CheckFunctionPointerDecl(ND->getType(), ND);
4792 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4793 if (VD->hasAttr<BlocksAttr>()) {
4794 static unsigned uniqueByrefDeclCount = 0;
4795 assert(!BlockByRefDeclNo.count(ND) &&
4796 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4797 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4798 RewriteByRefVar(VD);
4799 }
4800 else
4801 RewriteTypeOfDecl(VD);
4802 }
4803 }
4804 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4805 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4806 RewriteBlockPointerDecl(TD);
4807 else if (TD->getUnderlyingType()->isFunctionPointerType())
4808 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4809 }
4810 }
4811 }
4812
4813 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4814 RewriteObjCQualifiedInterfaceTypes(CE);
4815
4816 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4817 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4818 assert(!Stmts.empty() && "Statement stack is empty");
4819 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4820 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4821 && "Statement stack mismatch");
4822 Stmts.pop_back();
4823 }
4824 // Handle blocks rewriting.
4825 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4826 if (BDRE->isByRef())
4827 return RewriteBlockDeclRefExpr(BDRE);
4828 }
4829 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4830 ValueDecl *VD = DRE->getDecl();
4831 if (VD->hasAttr<BlocksAttr>())
4832 return RewriteBlockDeclRefExpr(DRE);
4833 if (HasLocalVariableExternalStorage(VD))
4834 return RewriteLocalVariableExternalStorage(DRE);
4835 }
4836
4837 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4838 if (CE->getCallee()->getType()->isBlockPointerType()) {
4839 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4840 ReplaceStmt(S, BlockCall);
4841 return BlockCall;
4842 }
4843 }
4844 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4845 RewriteCastExpr(CE);
4846 }
4847#if 0
4848 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4849 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4850 ICE->getSubExpr(),
4851 SourceLocation());
4852 // Get the new text.
4853 std::string SStr;
4854 llvm::raw_string_ostream Buf(SStr);
4855 Replacement->printPretty(Buf, *Context);
4856 const std::string &Str = Buf.str();
4857
4858 printf("CAST = %s\n", &Str[0]);
4859 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4860 delete S;
4861 return Replacement;
4862 }
4863#endif
4864 // Return this stmt unmodified.
4865 return S;
4866}
4867
4868void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4869 for (RecordDecl::field_iterator i = RD->field_begin(),
4870 e = RD->field_end(); i != e; ++i) {
4871 FieldDecl *FD = *i;
4872 if (isTopLevelBlockPointerType(FD->getType()))
4873 RewriteBlockPointerDecl(FD);
4874 if (FD->getType()->isObjCQualifiedIdType() ||
4875 FD->getType()->isObjCQualifiedInterfaceType())
4876 RewriteObjCQualifiedInterfaceTypes(FD);
4877 }
4878}
4879
4880/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4881/// main file of the input.
4882void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4883 switch (D->getKind()) {
4884 case Decl::Function: {
4885 FunctionDecl *FD = cast<FunctionDecl>(D);
4886 if (FD->isOverloadedOperator())
4887 return;
4888
4889 // Since function prototypes don't have ParmDecl's, we check the function
4890 // prototype. This enables us to rewrite function declarations and
4891 // definitions using the same code.
4892 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4893
4894 // FIXME: If this should support Obj-C++, support CXXTryStmt
4895 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4896 CurFunctionDef = FD;
4897 CurFunctionDeclToDeclareForBlock = FD;
4898 CurrentBody = Body;
4899 Body =
4900 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4901 FD->setBody(Body);
4902 CurrentBody = 0;
4903 if (PropParentMap) {
4904 delete PropParentMap;
4905 PropParentMap = 0;
4906 }
4907 // This synthesizes and inserts the block "impl" struct, invoke function,
4908 // and any copy/dispose helper functions.
4909 InsertBlockLiteralsWithinFunction(FD);
4910 CurFunctionDef = 0;
4911 CurFunctionDeclToDeclareForBlock = 0;
4912 }
4913 break;
4914 }
4915 case Decl::ObjCMethod: {
4916 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4917 if (CompoundStmt *Body = MD->getCompoundBody()) {
4918 CurMethodDef = MD;
4919 CurrentBody = Body;
4920 Body =
4921 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4922 MD->setBody(Body);
4923 CurrentBody = 0;
4924 if (PropParentMap) {
4925 delete PropParentMap;
4926 PropParentMap = 0;
4927 }
4928 InsertBlockLiteralsWithinMethod(MD);
4929 CurMethodDef = 0;
4930 }
4931 break;
4932 }
4933 case Decl::ObjCImplementation: {
4934 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4935 ClassImplementation.push_back(CI);
4936 break;
4937 }
4938 case Decl::ObjCCategoryImpl: {
4939 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4940 CategoryImplementation.push_back(CI);
4941 break;
4942 }
4943 case Decl::Var: {
4944 VarDecl *VD = cast<VarDecl>(D);
4945 RewriteObjCQualifiedInterfaceTypes(VD);
4946 if (isTopLevelBlockPointerType(VD->getType()))
4947 RewriteBlockPointerDecl(VD);
4948 else if (VD->getType()->isFunctionPointerType()) {
4949 CheckFunctionPointerDecl(VD->getType(), VD);
4950 if (VD->getInit()) {
4951 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4952 RewriteCastExpr(CE);
4953 }
4954 }
4955 } else if (VD->getType()->isRecordType()) {
4956 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4957 if (RD->isCompleteDefinition())
4958 RewriteRecordBody(RD);
4959 }
4960 if (VD->getInit()) {
4961 GlobalVarDecl = VD;
4962 CurrentBody = VD->getInit();
4963 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4964 CurrentBody = 0;
4965 if (PropParentMap) {
4966 delete PropParentMap;
4967 PropParentMap = 0;
4968 }
4969 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4970 GlobalVarDecl = 0;
4971
4972 // This is needed for blocks.
4973 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4974 RewriteCastExpr(CE);
4975 }
4976 }
4977 break;
4978 }
4979 case Decl::TypeAlias:
4980 case Decl::Typedef: {
4981 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4982 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4983 RewriteBlockPointerDecl(TD);
4984 else if (TD->getUnderlyingType()->isFunctionPointerType())
4985 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4986 }
4987 break;
4988 }
4989 case Decl::CXXRecord:
4990 case Decl::Record: {
4991 RecordDecl *RD = cast<RecordDecl>(D);
4992 if (RD->isCompleteDefinition())
4993 RewriteRecordBody(RD);
4994 break;
4995 }
4996 default:
4997 break;
4998 }
4999 // Nothing yet.
5000}
5001
5002void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5003 if (Diags.hasErrorOccurred())
5004 return;
5005
5006 RewriteInclude();
5007
5008 // Here's a great place to add any extra declarations that may be needed.
5009 // Write out meta data for each @protocol(<expr>).
5010 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5011 E = ProtocolExprDecls.end(); I != E; ++I)
5012 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5013
5014 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5015 if (ClassImplementation.size() || CategoryImplementation.size())
5016 RewriteImplementations();
5017
5018 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5019 // we are done.
5020 if (const RewriteBuffer *RewriteBuf =
5021 Rewrite.getRewriteBufferFor(MainFileID)) {
5022 //printf("Changed:\n");
5023 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5024 } else {
5025 llvm::errs() << "No changes\n";
5026 }
5027
5028 if (ClassImplementation.size() || CategoryImplementation.size() ||
5029 ProtocolExprDecls.size()) {
5030 // Rewrite Objective-c meta data*
5031 std::string ResultStr;
5032 RewriteMetaDataIntoBuffer(ResultStr);
5033 // Emit metadata.
5034 *OutFile << ResultStr;
5035 }
5036 OutFile->flush();
5037}
5038
5039void RewriteModernObjC::Initialize(ASTContext &context) {
5040 InitializeCommon(context);
5041
5042 // declaring objc_selector outside the parameter list removes a silly
5043 // scope related warning...
5044 if (IsHeader)
5045 Preamble = "#pragma once\n";
5046 Preamble += "struct objc_selector; struct objc_class;\n";
5047 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5048 Preamble += "struct objc_object *superClass; ";
5049 if (LangOpts.MicrosoftExt) {
5050 // Add a constructor for creating temporary objects.
5051 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5052 ": ";
5053 Preamble += "object(o), superClass(s) {} ";
5054 }
5055 Preamble += "};\n";
5056 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5057 Preamble += "typedef struct objc_object Protocol;\n";
5058 Preamble += "#define _REWRITER_typedef_Protocol\n";
5059 Preamble += "#endif\n";
5060 if (LangOpts.MicrosoftExt) {
5061 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5062 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5063 } else
5064 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5065 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5066 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5067 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5068 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5069 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5070 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5071 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5072 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5073 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5074 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5075 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5076 Preamble += "(const char *);\n";
5077 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5078 Preamble += "(struct objc_class *);\n";
5079 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5080 Preamble += "(const char *);\n";
5081 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5082 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5083 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5084 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5085 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5086 Preamble += "(struct objc_class *, struct objc_object *);\n";
5087 // @synchronized hooks.
5088 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5089 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5090 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5091 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5092 Preamble += "struct __objcFastEnumerationState {\n\t";
5093 Preamble += "unsigned long state;\n\t";
5094 Preamble += "void **itemsPtr;\n\t";
5095 Preamble += "unsigned long *mutationsPtr;\n\t";
5096 Preamble += "unsigned long extra[5];\n};\n";
5097 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5098 Preamble += "#define __FASTENUMERATIONSTATE\n";
5099 Preamble += "#endif\n";
5100 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5101 Preamble += "struct __NSConstantStringImpl {\n";
5102 Preamble += " int *isa;\n";
5103 Preamble += " int flags;\n";
5104 Preamble += " char *str;\n";
5105 Preamble += " long length;\n";
5106 Preamble += "};\n";
5107 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5108 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5109 Preamble += "#else\n";
5110 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5111 Preamble += "#endif\n";
5112 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5113 Preamble += "#endif\n";
5114 // Blocks preamble.
5115 Preamble += "#ifndef BLOCK_IMPL\n";
5116 Preamble += "#define BLOCK_IMPL\n";
5117 Preamble += "struct __block_impl {\n";
5118 Preamble += " void *isa;\n";
5119 Preamble += " int Flags;\n";
5120 Preamble += " int Reserved;\n";
5121 Preamble += " void *FuncPtr;\n";
5122 Preamble += "};\n";
5123 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5124 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5125 Preamble += "extern \"C\" __declspec(dllexport) "
5126 "void _Block_object_assign(void *, const void *, const int);\n";
5127 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5128 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5129 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5130 Preamble += "#else\n";
5131 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5132 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5133 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5134 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5135 Preamble += "#endif\n";
5136 Preamble += "#endif\n";
5137 if (LangOpts.MicrosoftExt) {
5138 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5139 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5140 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5141 Preamble += "#define __attribute__(X)\n";
5142 Preamble += "#endif\n";
5143 Preamble += "#define __weak\n";
5144 }
5145 else {
5146 Preamble += "#define __block\n";
5147 Preamble += "#define __weak\n";
5148 }
5149 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5150 // as this avoids warning in any 64bit/32bit compilation model.
5151 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5152}
5153
5154/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5155/// ivar offset.
5156void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5157 std::string &Result) {
5158 if (ivar->isBitField()) {
5159 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5160 // place all bitfields at offset 0.
5161 Result += "0";
5162 } else {
5163 Result += "__OFFSETOFIVAR__(struct ";
5164 Result += ivar->getContainingInterface()->getNameAsString();
5165 if (LangOpts.MicrosoftExt)
5166 Result += "_IMPL";
5167 Result += ", ";
5168 Result += ivar->getNameAsString();
5169 Result += ")";
5170 }
5171}
5172
5173/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5174/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005175/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005176/// char *attributes;
5177/// }
5178
5179/// struct _prop_list_t {
5180/// uint32_t entsize; // sizeof(struct _prop_t)
5181/// uint32_t count_of_properties;
5182/// struct _prop_t prop_list[count_of_properties];
5183/// }
5184
5185/// struct _protocol_t;
5186
5187/// struct _protocol_list_t {
5188/// long protocol_count; // Note, this is 32/64 bit
5189/// struct _protocol_t * protocol_list[protocol_count];
5190/// }
5191
5192/// struct _objc_method {
5193/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005194/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005195/// char *_imp;
5196/// }
5197
5198/// struct _method_list_t {
5199/// uint32_t entsize; // sizeof(struct _objc_method)
5200/// uint32_t method_count;
5201/// struct _objc_method method_list[method_count];
5202/// }
5203
5204/// struct _protocol_t {
5205/// id isa; // NULL
5206/// const char * const protocol_name;
5207/// const struct _protocol_list_t * protocol_list; // super protocols
5208/// const struct method_list_t * const instance_methods;
5209/// const struct method_list_t * const class_methods;
5210/// const struct method_list_t *optionalInstanceMethods;
5211/// const struct method_list_t *optionalClassMethods;
5212/// const struct _prop_list_t * properties;
5213/// const uint32_t size; // sizeof(struct _protocol_t)
5214/// const uint32_t flags; // = 0
5215/// const char ** extendedMethodTypes;
5216/// }
5217
5218static void WriteModernMetadataDeclarations(std::string &Result) {
5219 static bool meta_data_declared = false;
5220 if (meta_data_declared)
5221 return;
5222
5223 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005224 Result += "\tconst char *name;\n";
5225 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005226 Result += "};\n";
5227
5228 Result += "\nstruct _protocol_t;\n";
5229
5230 Result += "\nstruct _protocol_list_t {\n";
5231 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5232 Result += "\tstruct _protocol_t *protocol_list[/*protocol_count*/];\n";
5233 Result += "};\n";
5234
5235 Result += "\nstruct _objc_method {\n";
5236 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005237 Result += "\tconst char *method_type;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005238 Result += "\tchar *_imp;\n";
5239 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005240
5241 Result += "\nstruct _protocol_t {\n";
5242 Result += "\tvoid * isa; // NULL\n";
5243 Result += "\tconst char * const protocol_name;\n";
5244 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5245 Result += "\tconst struct method_list_t * const instance_methods;\n";
5246 Result += "\tconst struct method_list_t * const class_methods;\n";
5247 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5248 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5249 Result += "\tconst struct _prop_list_t * properties;\n";
5250 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5251 Result += "\tconst unsigned int flags; // = 0\n";
5252 Result += "\tconst char ** extendedMethodTypes;\n";
5253 Result += "};\n";
5254
5255 meta_data_declared = true;
5256}
5257
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005258static void Write_method_list_t_TypeDecl(std::string &Result,
5259 unsigned int method_count) {
5260 Result += "struct /*_method_list_t*/"; Result += " {\n";
5261 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5262 Result += "\tunsigned int method_count;\n";
5263 Result += "\tstruct _objc_method method_list[";
5264 Result += utostr(method_count); Result += "];\n";
5265 Result += "}";
5266}
5267
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005268static void Write__prop_list_t_TypeDecl(std::string &Result,
5269 unsigned int property_count) {
5270 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5271 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5272 Result += "\tunsigned int count_of_properties;\n";
5273 Result += "\tstruct _prop_t prop_list[";
5274 Result += utostr(property_count); Result += "];\n";
5275 Result += "}";
5276}
5277
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005278static void Write_method_list_t_initializer(ASTContext *Context, std::string &Result,
5279 ArrayRef<ObjCMethodDecl *> Methods,
5280 StringRef VarName,
5281 StringRef ProtocolName) {
5282 if (Methods.size() > 0) {
5283 Result += "\nstatic ";
5284 Write_method_list_t_TypeDecl(Result, Methods.size());
5285 Result += " "; Result += VarName;
5286 Result += ProtocolName;
5287 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5288 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5289 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5290 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5291 ObjCMethodDecl *MD = Methods[i];
5292 if (i == 0)
5293 Result += "\t{{(struct objc_selector *)\"";
5294 else
5295 Result += "\t{(struct objc_selector *)\"";
5296 Result += (MD)->getSelector().getAsString(); Result += "\"";
5297 Result += ", ";
5298 std::string MethodTypeString;
5299 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5300 Result += "\""; Result += MethodTypeString; Result += "\"";
5301 Result += ", ";
5302 // FIXME is _imp always null here?
5303 if (i == e-1)
5304 Result += "0}}\n";
5305 else
5306 Result += "0},\n";
5307 }
5308 Result += "};\n";
5309 }
5310}
5311
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005312static void Write__prop_list_t_initializer(RewriteModernObjC &RewriteObj,
5313 ASTContext *Context, std::string &Result,
5314 ArrayRef<ObjCPropertyDecl *> Properties,
5315 const Decl *Container,
5316 StringRef VarName,
5317 StringRef ProtocolName) {
5318 if (Properties.size() > 0) {
5319 Result += "\nstatic ";
5320 Write__prop_list_t_TypeDecl(Result, Properties.size());
5321 Result += " "; Result += VarName;
5322 Result += ProtocolName;
5323 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5324 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5325 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5326 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5327 ObjCPropertyDecl *PropDecl = Properties[i];
5328 if (i == 0)
5329 Result += "\t{{\"";
5330 else
5331 Result += "\t{\"";
5332 Result += PropDecl->getName(); Result += "\",";
5333 std::string PropertyTypeString, QuotePropertyTypeString;
5334 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5335 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5336 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5337 if (i == e-1)
5338 Result += "}}\n";
5339 else
5340 Result += "},\n";
5341 }
5342 Result += "};\n";
5343 }
5344}
5345
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005346/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5347void RewriteModernObjC::RewriteObjCProtocolMetaData(
5348 ObjCProtocolDecl *PDecl, StringRef prefix,
5349 StringRef ClassName, std::string &Result) {
5350 static bool objc_protocol_methods = false;
5351
5352 WriteModernMetadataDeclarations(Result);
5353
5354 // Output struct protocol_methods holder of method selector and type.
5355 if (!objc_protocol_methods && PDecl->hasDefinition()) {
5356 /* struct protocol_methods {
5357 SEL _cmd;
5358 char *method_types;
5359 }
5360 */
5361 Result += "\nstruct _protocol_methods {\n";
5362 Result += "\tstruct objc_selector *_cmd;\n";
5363 Result += "\tchar *method_types;\n";
5364 Result += "};\n";
5365
5366 objc_protocol_methods = true;
5367 }
5368 // Do not synthesize the protocol more than once.
5369 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5370 return;
5371
5372 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5373 PDecl = Def;
5374
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005375 // Construct method lists.
5376 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5377 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5378 for (ObjCProtocolDecl::instmeth_iterator
5379 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5380 I != E; ++I) {
5381 ObjCMethodDecl *MD = *I;
5382 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5383 OptInstanceMethods.push_back(MD);
5384 } else {
5385 InstanceMethods.push_back(MD);
5386 }
5387 }
5388
5389 for (ObjCProtocolDecl::classmeth_iterator
5390 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5391 I != E; ++I) {
5392 ObjCMethodDecl *MD = *I;
5393 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5394 OptClassMethods.push_back(MD);
5395 } else {
5396 ClassMethods.push_back(MD);
5397 }
5398 }
5399 Write_method_list_t_initializer(Context, Result, InstanceMethods,
5400 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
5401 PDecl->getNameAsString());
5402
5403 Write_method_list_t_initializer(Context, Result, ClassMethods,
5404 "_OBJC_PROTOCOL_CLASS_METHODS_",
5405 PDecl->getNameAsString());
5406
5407 Write_method_list_t_initializer(Context, Result, OptInstanceMethods,
5408 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
5409 PDecl->getNameAsString());
5410
5411 Write_method_list_t_initializer(Context, Result, OptClassMethods,
5412 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
5413 PDecl->getNameAsString());
5414
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005415 // Protocol's property metadata.
5416 std::vector<ObjCPropertyDecl *> ProtocolProperties;
5417 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
5418 E = PDecl->prop_end(); I != E; ++I)
5419 ProtocolProperties.push_back(*I);
5420
5421 Write__prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
5422 /* Container */0,
5423 "_OBJC_PROTOCOL_PROPERTIES_",
5424 PDecl->getNameAsString());
5425
5426
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005427
5428 // ====================================Legacy ABI ====================================================
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005429 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5430 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5431 PDecl->instmeth_end());
5432 /* struct _objc_protocol_method_list {
5433 int protocol_method_count;
5434 struct protocol_methods protocols[];
5435 }
5436 */
5437 Result += "\nstatic struct {\n";
5438 Result += "\tint protocol_method_count;\n";
5439 Result += "\tstruct _protocol_methods protocol_methods[";
5440 Result += utostr(NumMethods);
5441 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5442 Result += PDecl->getNameAsString();
5443 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5444 "{\n\t" + utostr(NumMethods) + "\n";
5445
5446 // Output instance methods declared in this protocol.
5447 for (ObjCProtocolDecl::instmeth_iterator
5448 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5449 I != E; ++I) {
5450 if (I == PDecl->instmeth_begin())
5451 Result += "\t ,{{(struct objc_selector *)\"";
5452 else
5453 Result += "\t ,{(struct objc_selector *)\"";
5454 Result += (*I)->getSelector().getAsString();
5455 std::string MethodTypeString;
5456 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5457 Result += "\", \"";
5458 Result += MethodTypeString;
5459 Result += "\"}\n";
5460 }
5461 Result += "\t }\n};\n";
5462 }
5463
5464 // Output class methods declared in this protocol.
5465 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5466 PDecl->classmeth_end());
5467 if (NumMethods > 0) {
5468 /* struct _objc_protocol_method_list {
5469 int protocol_method_count;
5470 struct protocol_methods protocols[];
5471 }
5472 */
5473 Result += "\nstatic struct {\n";
5474 Result += "\tint protocol_method_count;\n";
5475 Result += "\tstruct _protocol_methods protocol_methods[";
5476 Result += utostr(NumMethods);
5477 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5478 Result += PDecl->getNameAsString();
5479 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5480 "{\n\t";
5481 Result += utostr(NumMethods);
5482 Result += "\n";
5483
5484 // Output instance methods declared in this protocol.
5485 for (ObjCProtocolDecl::classmeth_iterator
5486 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5487 I != E; ++I) {
5488 if (I == PDecl->classmeth_begin())
5489 Result += "\t ,{{(struct objc_selector *)\"";
5490 else
5491 Result += "\t ,{(struct objc_selector *)\"";
5492 Result += (*I)->getSelector().getAsString();
5493 std::string MethodTypeString;
5494 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5495 Result += "\", \"";
5496 Result += MethodTypeString;
5497 Result += "\"}\n";
5498 }
5499 Result += "\t }\n};\n";
5500 }
5501
5502 // Output:
5503 /* struct _objc_protocol {
5504 // Objective-C 1.0 extensions
5505 struct _objc_protocol_extension *isa;
5506 char *protocol_name;
5507 struct _objc_protocol **protocol_list;
5508 struct _objc_protocol_method_list *instance_methods;
5509 struct _objc_protocol_method_list *class_methods;
5510 };
5511 */
5512 static bool objc_protocol = false;
5513 if (!objc_protocol) {
5514 Result += "\nstruct _objc_protocol {\n";
5515 Result += "\tstruct _objc_protocol_extension *isa;\n";
5516 Result += "\tchar *protocol_name;\n";
5517 Result += "\tstruct _objc_protocol **protocol_list;\n";
5518 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5519 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5520 Result += "};\n";
5521
5522 objc_protocol = true;
5523 }
5524
5525 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5526 Result += PDecl->getNameAsString();
5527 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5528 "{\n\t0, \"";
5529 Result += PDecl->getNameAsString();
5530 Result += "\", 0, ";
5531 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5532 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5533 Result += PDecl->getNameAsString();
5534 Result += ", ";
5535 }
5536 else
5537 Result += "0, ";
5538 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5539 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5540 Result += PDecl->getNameAsString();
5541 Result += "\n";
5542 }
5543 else
5544 Result += "0\n";
5545 Result += "};\n";
5546
5547 // Mark this protocol as having been generated.
5548 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
5549 llvm_unreachable("protocol already synthesized");
5550
5551}
5552
5553void RewriteModernObjC::RewriteObjCProtocolListMetaData(
5554 const ObjCList<ObjCProtocolDecl> &Protocols,
5555 StringRef prefix, StringRef ClassName,
5556 std::string &Result) {
5557 if (Protocols.empty()) return;
5558
5559 for (unsigned i = 0; i != Protocols.size(); i++)
5560 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5561
5562 // Output the top lovel protocol meta-data for the class.
5563 /* struct _objc_protocol_list {
5564 struct _objc_protocol_list *next;
5565 int protocol_count;
5566 struct _objc_protocol *class_protocols[];
5567 }
5568 */
5569 Result += "\nstatic struct {\n";
5570 Result += "\tstruct _objc_protocol_list *next;\n";
5571 Result += "\tint protocol_count;\n";
5572 Result += "\tstruct _objc_protocol *class_protocols[";
5573 Result += utostr(Protocols.size());
5574 Result += "];\n} _OBJC_";
5575 Result += prefix;
5576 Result += "_PROTOCOLS_";
5577 Result += ClassName;
5578 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5579 "{\n\t0, ";
5580 Result += utostr(Protocols.size());
5581 Result += "\n";
5582
5583 Result += "\t,{&_OBJC_PROTOCOL_";
5584 Result += Protocols[0]->getNameAsString();
5585 Result += " \n";
5586
5587 for (unsigned i = 1; i != Protocols.size(); i++) {
5588 Result += "\t ,&_OBJC_PROTOCOL_";
5589 Result += Protocols[i]->getNameAsString();
5590 Result += "\n";
5591 }
5592 Result += "\t }\n};\n";
5593}
5594
5595void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5596 std::string &Result) {
5597 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5598
5599 // Explicitly declared @interface's are already synthesized.
5600 if (CDecl->isImplicitInterfaceDecl()) {
5601 // FIXME: Implementation of a class with no @interface (legacy) does not
5602 // produce correct synthesis as yet.
5603 RewriteObjCInternalStruct(CDecl, Result);
5604 }
5605
5606 // Build _objc_ivar_list metadata for classes ivars if needed
5607 unsigned NumIvars = !IDecl->ivar_empty()
5608 ? IDecl->ivar_size()
5609 : (CDecl ? CDecl->ivar_size() : 0);
5610 if (NumIvars > 0) {
5611 static bool objc_ivar = false;
5612 if (!objc_ivar) {
5613 /* struct _objc_ivar {
5614 char *ivar_name;
5615 char *ivar_type;
5616 int ivar_offset;
5617 };
5618 */
5619 Result += "\nstruct _objc_ivar {\n";
5620 Result += "\tchar *ivar_name;\n";
5621 Result += "\tchar *ivar_type;\n";
5622 Result += "\tint ivar_offset;\n";
5623 Result += "};\n";
5624
5625 objc_ivar = true;
5626 }
5627
5628 /* struct {
5629 int ivar_count;
5630 struct _objc_ivar ivar_list[nIvars];
5631 };
5632 */
5633 Result += "\nstatic struct {\n";
5634 Result += "\tint ivar_count;\n";
5635 Result += "\tstruct _objc_ivar ivar_list[";
5636 Result += utostr(NumIvars);
5637 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5638 Result += IDecl->getNameAsString();
5639 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5640 "{\n\t";
5641 Result += utostr(NumIvars);
5642 Result += "\n";
5643
5644 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5645 SmallVector<ObjCIvarDecl *, 8> IVars;
5646 if (!IDecl->ivar_empty()) {
5647 for (ObjCInterfaceDecl::ivar_iterator
5648 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5649 IV != IVEnd; ++IV)
5650 IVars.push_back(*IV);
5651 IVI = IDecl->ivar_begin();
5652 IVE = IDecl->ivar_end();
5653 } else {
5654 IVI = CDecl->ivar_begin();
5655 IVE = CDecl->ivar_end();
5656 }
5657 Result += "\t,{{\"";
5658 Result += (*IVI)->getNameAsString();
5659 Result += "\", \"";
5660 std::string TmpString, StrEncoding;
5661 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5662 QuoteDoublequotes(TmpString, StrEncoding);
5663 Result += StrEncoding;
5664 Result += "\", ";
5665 RewriteIvarOffsetComputation(*IVI, Result);
5666 Result += "}\n";
5667 for (++IVI; IVI != IVE; ++IVI) {
5668 Result += "\t ,{\"";
5669 Result += (*IVI)->getNameAsString();
5670 Result += "\", \"";
5671 std::string TmpString, StrEncoding;
5672 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5673 QuoteDoublequotes(TmpString, StrEncoding);
5674 Result += StrEncoding;
5675 Result += "\", ";
5676 RewriteIvarOffsetComputation((*IVI), Result);
5677 Result += "}\n";
5678 }
5679
5680 Result += "\t }\n};\n";
5681 }
5682
5683 // Build _objc_method_list for class's instance methods if needed
5684 SmallVector<ObjCMethodDecl *, 32>
5685 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5686
5687 // If any of our property implementations have associated getters or
5688 // setters, produce metadata for them as well.
5689 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5690 PropEnd = IDecl->propimpl_end();
5691 Prop != PropEnd; ++Prop) {
5692 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5693 continue;
5694 if (!(*Prop)->getPropertyIvarDecl())
5695 continue;
5696 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5697 if (!PD)
5698 continue;
5699 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5700 if (!Getter->isDefined())
5701 InstanceMethods.push_back(Getter);
5702 if (PD->isReadOnly())
5703 continue;
5704 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5705 if (!Setter->isDefined())
5706 InstanceMethods.push_back(Setter);
5707 }
5708 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5709 true, "", IDecl->getName(), Result);
5710
5711 // Build _objc_method_list for class's class methods if needed
5712 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5713 false, "", IDecl->getName(), Result);
5714
5715 // Protocols referenced in class declaration?
5716 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5717 "CLASS", CDecl->getName(), Result);
5718
5719 // Declaration of class/meta-class metadata
5720 /* struct _objc_class {
5721 struct _objc_class *isa; // or const char *root_class_name when metadata
5722 const char *super_class_name;
5723 char *name;
5724 long version;
5725 long info;
5726 long instance_size;
5727 struct _objc_ivar_list *ivars;
5728 struct _objc_method_list *methods;
5729 struct objc_cache *cache;
5730 struct objc_protocol_list *protocols;
5731 const char *ivar_layout;
5732 struct _objc_class_ext *ext;
5733 };
5734 */
5735 static bool objc_class = false;
5736 if (!objc_class) {
5737 Result += "\nstruct _objc_class {\n";
5738 Result += "\tstruct _objc_class *isa;\n";
5739 Result += "\tconst char *super_class_name;\n";
5740 Result += "\tchar *name;\n";
5741 Result += "\tlong version;\n";
5742 Result += "\tlong info;\n";
5743 Result += "\tlong instance_size;\n";
5744 Result += "\tstruct _objc_ivar_list *ivars;\n";
5745 Result += "\tstruct _objc_method_list *methods;\n";
5746 Result += "\tstruct objc_cache *cache;\n";
5747 Result += "\tstruct _objc_protocol_list *protocols;\n";
5748 Result += "\tconst char *ivar_layout;\n";
5749 Result += "\tstruct _objc_class_ext *ext;\n";
5750 Result += "};\n";
5751 objc_class = true;
5752 }
5753
5754 // Meta-class metadata generation.
5755 ObjCInterfaceDecl *RootClass = 0;
5756 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5757 while (SuperClass) {
5758 RootClass = SuperClass;
5759 SuperClass = SuperClass->getSuperClass();
5760 }
5761 SuperClass = CDecl->getSuperClass();
5762
5763 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5764 Result += CDecl->getNameAsString();
5765 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5766 "{\n\t(struct _objc_class *)\"";
5767 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5768 Result += "\"";
5769
5770 if (SuperClass) {
5771 Result += ", \"";
5772 Result += SuperClass->getNameAsString();
5773 Result += "\", \"";
5774 Result += CDecl->getNameAsString();
5775 Result += "\"";
5776 }
5777 else {
5778 Result += ", 0, \"";
5779 Result += CDecl->getNameAsString();
5780 Result += "\"";
5781 }
5782 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5783 // 'info' field is initialized to CLS_META(2) for metaclass
5784 Result += ", 0,2, sizeof(struct _objc_class), 0";
5785 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5786 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5787 Result += IDecl->getNameAsString();
5788 Result += "\n";
5789 }
5790 else
5791 Result += ", 0\n";
5792 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5793 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5794 Result += CDecl->getNameAsString();
5795 Result += ",0,0\n";
5796 }
5797 else
5798 Result += "\t,0,0,0,0\n";
5799 Result += "};\n";
5800
5801 // class metadata generation.
5802 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5803 Result += CDecl->getNameAsString();
5804 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5805 "{\n\t&_OBJC_METACLASS_";
5806 Result += CDecl->getNameAsString();
5807 if (SuperClass) {
5808 Result += ", \"";
5809 Result += SuperClass->getNameAsString();
5810 Result += "\", \"";
5811 Result += CDecl->getNameAsString();
5812 Result += "\"";
5813 }
5814 else {
5815 Result += ", 0, \"";
5816 Result += CDecl->getNameAsString();
5817 Result += "\"";
5818 }
5819 // 'info' field is initialized to CLS_CLASS(1) for class
5820 Result += ", 0,1";
5821 if (!ObjCSynthesizedStructs.count(CDecl))
5822 Result += ",0";
5823 else {
5824 // class has size. Must synthesize its size.
5825 Result += ",sizeof(struct ";
5826 Result += CDecl->getNameAsString();
5827 if (LangOpts.MicrosoftExt)
5828 Result += "_IMPL";
5829 Result += ")";
5830 }
5831 if (NumIvars > 0) {
5832 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5833 Result += CDecl->getNameAsString();
5834 Result += "\n\t";
5835 }
5836 else
5837 Result += ",0";
5838 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5839 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5840 Result += CDecl->getNameAsString();
5841 Result += ", 0\n\t";
5842 }
5843 else
5844 Result += ",0,0";
5845 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5846 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5847 Result += CDecl->getNameAsString();
5848 Result += ", 0,0\n";
5849 }
5850 else
5851 Result += ",0,0,0\n";
5852 Result += "};\n";
5853}
5854
5855void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
5856 int ClsDefCount = ClassImplementation.size();
5857 int CatDefCount = CategoryImplementation.size();
5858
5859 // For each implemented class, write out all its meta data.
5860 for (int i = 0; i < ClsDefCount; i++)
5861 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5862
5863 // For each implemented category, write out all its meta data.
5864 for (int i = 0; i < CatDefCount; i++)
5865 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5866
5867 // Write objc_symtab metadata
5868 /*
5869 struct _objc_symtab
5870 {
5871 long sel_ref_cnt;
5872 SEL *refs;
5873 short cls_def_cnt;
5874 short cat_def_cnt;
5875 void *defs[cls_def_cnt + cat_def_cnt];
5876 };
5877 */
5878
5879 Result += "\nstruct _objc_symtab {\n";
5880 Result += "\tlong sel_ref_cnt;\n";
5881 Result += "\tSEL *refs;\n";
5882 Result += "\tshort cls_def_cnt;\n";
5883 Result += "\tshort cat_def_cnt;\n";
5884 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5885 Result += "};\n\n";
5886
5887 Result += "static struct _objc_symtab "
5888 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5889 Result += "\t0, 0, " + utostr(ClsDefCount)
5890 + ", " + utostr(CatDefCount) + "\n";
5891 for (int i = 0; i < ClsDefCount; i++) {
5892 Result += "\t,&_OBJC_CLASS_";
5893 Result += ClassImplementation[i]->getNameAsString();
5894 Result += "\n";
5895 }
5896
5897 for (int i = 0; i < CatDefCount; i++) {
5898 Result += "\t,&_OBJC_CATEGORY_";
5899 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5900 Result += "_";
5901 Result += CategoryImplementation[i]->getNameAsString();
5902 Result += "\n";
5903 }
5904
5905 Result += "};\n\n";
5906
5907 // Write objc_module metadata
5908
5909 /*
5910 struct _objc_module {
5911 long version;
5912 long size;
5913 const char *name;
5914 struct _objc_symtab *symtab;
5915 }
5916 */
5917
5918 Result += "\nstruct _objc_module {\n";
5919 Result += "\tlong version;\n";
5920 Result += "\tlong size;\n";
5921 Result += "\tconst char *name;\n";
5922 Result += "\tstruct _objc_symtab *symtab;\n";
5923 Result += "};\n\n";
5924 Result += "static struct _objc_module "
5925 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5926 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5927 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5928 Result += "};\n\n";
5929
5930 if (LangOpts.MicrosoftExt) {
5931 if (ProtocolExprDecls.size()) {
5932 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5933 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5934 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5935 E = ProtocolExprDecls.end(); I != E; ++I) {
5936 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5937 Result += (*I)->getNameAsString();
5938 Result += " = &_OBJC_PROTOCOL_";
5939 Result += (*I)->getNameAsString();
5940 Result += ";\n";
5941 }
5942 Result += "#pragma data_seg(pop)\n\n";
5943 }
5944 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5945 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5946 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5947 Result += "&_OBJC_MODULES;\n";
5948 Result += "#pragma data_seg(pop)\n\n";
5949 }
5950}
5951
5952/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5953/// implementation.
5954void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5955 std::string &Result) {
5956 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5957 // Find category declaration for this implementation.
5958 ObjCCategoryDecl *CDecl;
5959 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5960 CDecl = CDecl->getNextClassCategory())
5961 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5962 break;
5963
5964 std::string FullCategoryName = ClassDecl->getNameAsString();
5965 FullCategoryName += '_';
5966 FullCategoryName += IDecl->getNameAsString();
5967
5968 // Build _objc_method_list for class's instance methods if needed
5969 SmallVector<ObjCMethodDecl *, 32>
5970 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5971
5972 // If any of our property implementations have associated getters or
5973 // setters, produce metadata for them as well.
5974 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5975 PropEnd = IDecl->propimpl_end();
5976 Prop != PropEnd; ++Prop) {
5977 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5978 continue;
5979 if (!(*Prop)->getPropertyIvarDecl())
5980 continue;
5981 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5982 if (!PD)
5983 continue;
5984 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5985 InstanceMethods.push_back(Getter);
5986 if (PD->isReadOnly())
5987 continue;
5988 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5989 InstanceMethods.push_back(Setter);
5990 }
5991 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5992 true, "CATEGORY_", FullCategoryName.c_str(),
5993 Result);
5994
5995 // Build _objc_method_list for class's class methods if needed
5996 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5997 false, "CATEGORY_", FullCategoryName.c_str(),
5998 Result);
5999
6000 // Protocols referenced in class declaration?
6001 // Null CDecl is case of a category implementation with no category interface
6002 if (CDecl)
6003 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
6004 FullCategoryName, Result);
6005 /* struct _objc_category {
6006 char *category_name;
6007 char *class_name;
6008 struct _objc_method_list *instance_methods;
6009 struct _objc_method_list *class_methods;
6010 struct _objc_protocol_list *protocols;
6011 // Objective-C 1.0 extensions
6012 uint32_t size; // sizeof (struct _objc_category)
6013 struct _objc_property_list *instance_properties; // category's own
6014 // @property decl.
6015 };
6016 */
6017
6018 static bool objc_category = false;
6019 if (!objc_category) {
6020 Result += "\nstruct _objc_category {\n";
6021 Result += "\tchar *category_name;\n";
6022 Result += "\tchar *class_name;\n";
6023 Result += "\tstruct _objc_method_list *instance_methods;\n";
6024 Result += "\tstruct _objc_method_list *class_methods;\n";
6025 Result += "\tstruct _objc_protocol_list *protocols;\n";
6026 Result += "\tunsigned int size;\n";
6027 Result += "\tstruct _objc_property_list *instance_properties;\n";
6028 Result += "};\n";
6029 objc_category = true;
6030 }
6031 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
6032 Result += FullCategoryName;
6033 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
6034 Result += IDecl->getNameAsString();
6035 Result += "\"\n\t, \"";
6036 Result += ClassDecl->getNameAsString();
6037 Result += "\"\n";
6038
6039 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
6040 Result += "\t, (struct _objc_method_list *)"
6041 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
6042 Result += FullCategoryName;
6043 Result += "\n";
6044 }
6045 else
6046 Result += "\t, 0\n";
6047 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
6048 Result += "\t, (struct _objc_method_list *)"
6049 "&_OBJC_CATEGORY_CLASS_METHODS_";
6050 Result += FullCategoryName;
6051 Result += "\n";
6052 }
6053 else
6054 Result += "\t, 0\n";
6055
6056 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
6057 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
6058 Result += FullCategoryName;
6059 Result += "\n";
6060 }
6061 else
6062 Result += "\t, 0\n";
6063 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
6064}
6065
6066// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6067/// class methods.
6068template<typename MethodIterator>
6069void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6070 MethodIterator MethodEnd,
6071 bool IsInstanceMethod,
6072 StringRef prefix,
6073 StringRef ClassName,
6074 std::string &Result) {
6075 if (MethodBegin == MethodEnd) return;
6076
6077 if (!objc_impl_method) {
6078 /* struct _objc_method {
6079 SEL _cmd;
6080 char *method_types;
6081 void *_imp;
6082 }
6083 */
6084 Result += "\nstruct _objc_method {\n";
6085 Result += "\tSEL _cmd;\n";
6086 Result += "\tchar *method_types;\n";
6087 Result += "\tvoid *_imp;\n";
6088 Result += "};\n";
6089
6090 objc_impl_method = true;
6091 }
6092
6093 // Build _objc_method_list for class's methods if needed
6094
6095 /* struct {
6096 struct _objc_method_list *next_method;
6097 int method_count;
6098 struct _objc_method method_list[];
6099 }
6100 */
6101 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
6102 Result += "\nstatic struct {\n";
6103 Result += "\tstruct _objc_method_list *next_method;\n";
6104 Result += "\tint method_count;\n";
6105 Result += "\tstruct _objc_method method_list[";
6106 Result += utostr(NumMethods);
6107 Result += "];\n} _OBJC_";
6108 Result += prefix;
6109 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6110 Result += "_METHODS_";
6111 Result += ClassName;
6112 Result += " __attribute__ ((used, section (\"__OBJC, __";
6113 Result += IsInstanceMethod ? "inst" : "cls";
6114 Result += "_meth\")))= ";
6115 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6116
6117 Result += "\t,{{(SEL)\"";
6118 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6119 std::string MethodTypeString;
6120 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6121 Result += "\", \"";
6122 Result += MethodTypeString;
6123 Result += "\", (void *)";
6124 Result += MethodInternalNames[*MethodBegin];
6125 Result += "}\n";
6126 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6127 Result += "\t ,{(SEL)\"";
6128 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6129 std::string MethodTypeString;
6130 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6131 Result += "\", \"";
6132 Result += MethodTypeString;
6133 Result += "\", (void *)";
6134 Result += MethodInternalNames[*MethodBegin];
6135 Result += "}\n";
6136 }
6137 Result += "\t }\n};\n";
6138}
6139
6140Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6141 SourceRange OldRange = IV->getSourceRange();
6142 Expr *BaseExpr = IV->getBase();
6143
6144 // Rewrite the base, but without actually doing replaces.
6145 {
6146 DisableReplaceStmtScope S(*this);
6147 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6148 IV->setBase(BaseExpr);
6149 }
6150
6151 ObjCIvarDecl *D = IV->getDecl();
6152
6153 Expr *Replacement = IV;
6154 if (CurMethodDef) {
6155 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6156 const ObjCInterfaceType *iFaceDecl =
6157 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6158 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6159 // lookup which class implements the instance variable.
6160 ObjCInterfaceDecl *clsDeclared = 0;
6161 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6162 clsDeclared);
6163 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6164
6165 // Synthesize an explicit cast to gain access to the ivar.
6166 std::string RecName = clsDeclared->getIdentifier()->getName();
6167 RecName += "_IMPL";
6168 IdentifierInfo *II = &Context->Idents.get(RecName);
6169 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6170 SourceLocation(), SourceLocation(),
6171 II);
6172 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6173 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6174 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6175 CK_BitCast,
6176 IV->getBase());
6177 // Don't forget the parens to enforce the proper binding.
6178 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
6179 OldRange.getEnd(),
6180 castExpr);
6181 if (IV->isFreeIvar() &&
6182 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
6183 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
6184 IV->getLocation(),
6185 D->getType(),
6186 VK_LValue, OK_Ordinary);
6187 Replacement = ME;
6188 } else {
6189 IV->setBase(PE);
6190 }
6191 }
6192 } else { // we are outside a method.
6193 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
6194
6195 // Explicit ivar refs need to have a cast inserted.
6196 // FIXME: consider sharing some of this code with the code above.
6197 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6198 const ObjCInterfaceType *iFaceDecl =
6199 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6200 // lookup which class implements the instance variable.
6201 ObjCInterfaceDecl *clsDeclared = 0;
6202 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6203 clsDeclared);
6204 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6205
6206 // Synthesize an explicit cast to gain access to the ivar.
6207 std::string RecName = clsDeclared->getIdentifier()->getName();
6208 RecName += "_IMPL";
6209 IdentifierInfo *II = &Context->Idents.get(RecName);
6210 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6211 SourceLocation(), SourceLocation(),
6212 II);
6213 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6214 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6215 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6216 CK_BitCast,
6217 IV->getBase());
6218 // Don't forget the parens to enforce the proper binding.
6219 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6220 IV->getBase()->getLocEnd(), castExpr);
6221 // Cannot delete IV->getBase(), since PE points to it.
6222 // Replace the old base with the cast. This is important when doing
6223 // embedded rewrites. For example, [newInv->_container addObject:0].
6224 IV->setBase(PE);
6225 }
6226 }
6227
6228 ReplaceStmtWithRange(IV, Replacement, OldRange);
6229 return Replacement;
6230}
6231