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