blob: d67483a4947cfbb1e14f4ea8b6ce93b32335b41f [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";
1205 // Mark this typedef as having been generated.
1206 ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
1207 }
1208 RewriteObjCInternalStruct(ClassDecl, ResultStr);
1209
1210 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
1211 E = ClassDecl->prop_end(); I != E; ++I)
1212 RewriteProperty(*I);
1213 for (ObjCInterfaceDecl::instmeth_iterator
1214 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
1215 I != E; ++I)
1216 RewriteMethodDeclaration(*I);
1217 for (ObjCInterfaceDecl::classmeth_iterator
1218 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
1219 I != E; ++I)
1220 RewriteMethodDeclaration(*I);
1221
1222 // Lastly, comment out the @end.
1223 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1224 "/* @end */");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001225 // Mark this struct as having been generated.
1226 if (!ObjCSynthesizedStructs.insert(ClassDecl))
1227 llvm_unreachable("struct already synthesize- RewriteInterfaceDecl");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001228}
1229
1230Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1231 SourceRange OldRange = PseudoOp->getSourceRange();
1232
1233 // We just magically know some things about the structure of this
1234 // expression.
1235 ObjCMessageExpr *OldMsg =
1236 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1237 PseudoOp->getNumSemanticExprs() - 1));
1238
1239 // Because the rewriter doesn't allow us to rewrite rewritten code,
1240 // we need to suppress rewriting the sub-statements.
1241 Expr *Base, *RHS;
1242 {
1243 DisableReplaceStmtScope S(*this);
1244
1245 // Rebuild the base expression if we have one.
1246 Base = 0;
1247 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1248 Base = OldMsg->getInstanceReceiver();
1249 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1250 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1251 }
1252
1253 // Rebuild the RHS.
1254 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1255 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1256 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1257 }
1258
1259 // TODO: avoid this copy.
1260 SmallVector<SourceLocation, 1> SelLocs;
1261 OldMsg->getSelectorLocs(SelLocs);
1262
1263 ObjCMessageExpr *NewMsg = 0;
1264 switch (OldMsg->getReceiverKind()) {
1265 case ObjCMessageExpr::Class:
1266 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1267 OldMsg->getValueKind(),
1268 OldMsg->getLeftLoc(),
1269 OldMsg->getClassReceiverTypeInfo(),
1270 OldMsg->getSelector(),
1271 SelLocs,
1272 OldMsg->getMethodDecl(),
1273 RHS,
1274 OldMsg->getRightLoc(),
1275 OldMsg->isImplicit());
1276 break;
1277
1278 case ObjCMessageExpr::Instance:
1279 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1280 OldMsg->getValueKind(),
1281 OldMsg->getLeftLoc(),
1282 Base,
1283 OldMsg->getSelector(),
1284 SelLocs,
1285 OldMsg->getMethodDecl(),
1286 RHS,
1287 OldMsg->getRightLoc(),
1288 OldMsg->isImplicit());
1289 break;
1290
1291 case ObjCMessageExpr::SuperClass:
1292 case ObjCMessageExpr::SuperInstance:
1293 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1294 OldMsg->getValueKind(),
1295 OldMsg->getLeftLoc(),
1296 OldMsg->getSuperLoc(),
1297 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1298 OldMsg->getSuperType(),
1299 OldMsg->getSelector(),
1300 SelLocs,
1301 OldMsg->getMethodDecl(),
1302 RHS,
1303 OldMsg->getRightLoc(),
1304 OldMsg->isImplicit());
1305 break;
1306 }
1307
1308 Stmt *Replacement = SynthMessageExpr(NewMsg);
1309 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1310 return Replacement;
1311}
1312
1313Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1314 SourceRange OldRange = PseudoOp->getSourceRange();
1315
1316 // We just magically know some things about the structure of this
1317 // expression.
1318 ObjCMessageExpr *OldMsg =
1319 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1320
1321 // Because the rewriter doesn't allow us to rewrite rewritten code,
1322 // we need to suppress rewriting the sub-statements.
1323 Expr *Base = 0;
1324 {
1325 DisableReplaceStmtScope S(*this);
1326
1327 // Rebuild the base expression if we have one.
1328 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1329 Base = OldMsg->getInstanceReceiver();
1330 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1331 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1332 }
1333 }
1334
1335 // Intentionally empty.
1336 SmallVector<SourceLocation, 1> SelLocs;
1337 SmallVector<Expr*, 1> Args;
1338
1339 ObjCMessageExpr *NewMsg = 0;
1340 switch (OldMsg->getReceiverKind()) {
1341 case ObjCMessageExpr::Class:
1342 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1343 OldMsg->getValueKind(),
1344 OldMsg->getLeftLoc(),
1345 OldMsg->getClassReceiverTypeInfo(),
1346 OldMsg->getSelector(),
1347 SelLocs,
1348 OldMsg->getMethodDecl(),
1349 Args,
1350 OldMsg->getRightLoc(),
1351 OldMsg->isImplicit());
1352 break;
1353
1354 case ObjCMessageExpr::Instance:
1355 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1356 OldMsg->getValueKind(),
1357 OldMsg->getLeftLoc(),
1358 Base,
1359 OldMsg->getSelector(),
1360 SelLocs,
1361 OldMsg->getMethodDecl(),
1362 Args,
1363 OldMsg->getRightLoc(),
1364 OldMsg->isImplicit());
1365 break;
1366
1367 case ObjCMessageExpr::SuperClass:
1368 case ObjCMessageExpr::SuperInstance:
1369 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1370 OldMsg->getValueKind(),
1371 OldMsg->getLeftLoc(),
1372 OldMsg->getSuperLoc(),
1373 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1374 OldMsg->getSuperType(),
1375 OldMsg->getSelector(),
1376 SelLocs,
1377 OldMsg->getMethodDecl(),
1378 Args,
1379 OldMsg->getRightLoc(),
1380 OldMsg->isImplicit());
1381 break;
1382 }
1383
1384 Stmt *Replacement = SynthMessageExpr(NewMsg);
1385 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1386 return Replacement;
1387}
1388
1389/// SynthCountByEnumWithState - To print:
1390/// ((unsigned int (*)
1391/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1392/// (void *)objc_msgSend)((id)l_collection,
1393/// sel_registerName(
1394/// "countByEnumeratingWithState:objects:count:"),
1395/// &enumState,
1396/// (id *)__rw_items, (unsigned int)16)
1397///
1398void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1399 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1400 "id *, unsigned int))(void *)objc_msgSend)";
1401 buf += "\n\t\t";
1402 buf += "((id)l_collection,\n\t\t";
1403 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1404 buf += "\n\t\t";
1405 buf += "&enumState, "
1406 "(id *)__rw_items, (unsigned int)16)";
1407}
1408
1409/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1410/// statement to exit to its outer synthesized loop.
1411///
1412Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1413 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1414 return S;
1415 // replace break with goto __break_label
1416 std::string buf;
1417
1418 SourceLocation startLoc = S->getLocStart();
1419 buf = "goto __break_label_";
1420 buf += utostr(ObjCBcLabelNo.back());
1421 ReplaceText(startLoc, strlen("break"), buf);
1422
1423 return 0;
1424}
1425
1426/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1427/// statement to continue with its inner synthesized loop.
1428///
1429Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1430 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1431 return S;
1432 // replace continue with goto __continue_label
1433 std::string buf;
1434
1435 SourceLocation startLoc = S->getLocStart();
1436 buf = "goto __continue_label_";
1437 buf += utostr(ObjCBcLabelNo.back());
1438 ReplaceText(startLoc, strlen("continue"), buf);
1439
1440 return 0;
1441}
1442
1443/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1444/// It rewrites:
1445/// for ( type elem in collection) { stmts; }
1446
1447/// Into:
1448/// {
1449/// type elem;
1450/// struct __objcFastEnumerationState enumState = { 0 };
1451/// id __rw_items[16];
1452/// id l_collection = (id)collection;
1453/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1454/// objects:__rw_items count:16];
1455/// if (limit) {
1456/// unsigned long startMutations = *enumState.mutationsPtr;
1457/// do {
1458/// unsigned long counter = 0;
1459/// do {
1460/// if (startMutations != *enumState.mutationsPtr)
1461/// objc_enumerationMutation(l_collection);
1462/// elem = (type)enumState.itemsPtr[counter++];
1463/// stmts;
1464/// __continue_label: ;
1465/// } while (counter < limit);
1466/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1467/// objects:__rw_items count:16]);
1468/// elem = nil;
1469/// __break_label: ;
1470/// }
1471/// else
1472/// elem = nil;
1473/// }
1474///
1475Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1476 SourceLocation OrigEnd) {
1477 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1478 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1479 "ObjCForCollectionStmt Statement stack mismatch");
1480 assert(!ObjCBcLabelNo.empty() &&
1481 "ObjCForCollectionStmt - Label No stack empty");
1482
1483 SourceLocation startLoc = S->getLocStart();
1484 const char *startBuf = SM->getCharacterData(startLoc);
1485 StringRef elementName;
1486 std::string elementTypeAsString;
1487 std::string buf;
1488 buf = "\n{\n\t";
1489 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1490 // type elem;
1491 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1492 QualType ElementType = cast<ValueDecl>(D)->getType();
1493 if (ElementType->isObjCQualifiedIdType() ||
1494 ElementType->isObjCQualifiedInterfaceType())
1495 // Simply use 'id' for all qualified types.
1496 elementTypeAsString = "id";
1497 else
1498 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1499 buf += elementTypeAsString;
1500 buf += " ";
1501 elementName = D->getName();
1502 buf += elementName;
1503 buf += ";\n\t";
1504 }
1505 else {
1506 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1507 elementName = DR->getDecl()->getName();
1508 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1509 if (VD->getType()->isObjCQualifiedIdType() ||
1510 VD->getType()->isObjCQualifiedInterfaceType())
1511 // Simply use 'id' for all qualified types.
1512 elementTypeAsString = "id";
1513 else
1514 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1515 }
1516
1517 // struct __objcFastEnumerationState enumState = { 0 };
1518 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1519 // id __rw_items[16];
1520 buf += "id __rw_items[16];\n\t";
1521 // id l_collection = (id)
1522 buf += "id l_collection = (id)";
1523 // Find start location of 'collection' the hard way!
1524 const char *startCollectionBuf = startBuf;
1525 startCollectionBuf += 3; // skip 'for'
1526 startCollectionBuf = strchr(startCollectionBuf, '(');
1527 startCollectionBuf++; // skip '('
1528 // find 'in' and skip it.
1529 while (*startCollectionBuf != ' ' ||
1530 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1531 (*(startCollectionBuf+3) != ' ' &&
1532 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1533 startCollectionBuf++;
1534 startCollectionBuf += 3;
1535
1536 // Replace: "for (type element in" with string constructed thus far.
1537 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1538 // Replace ')' in for '(' type elem in collection ')' with ';'
1539 SourceLocation rightParenLoc = S->getRParenLoc();
1540 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1541 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1542 buf = ";\n\t";
1543
1544 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1545 // objects:__rw_items count:16];
1546 // which is synthesized into:
1547 // unsigned int limit =
1548 // ((unsigned int (*)
1549 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1550 // (void *)objc_msgSend)((id)l_collection,
1551 // sel_registerName(
1552 // "countByEnumeratingWithState:objects:count:"),
1553 // (struct __objcFastEnumerationState *)&state,
1554 // (id *)__rw_items, (unsigned int)16);
1555 buf += "unsigned long limit =\n\t\t";
1556 SynthCountByEnumWithState(buf);
1557 buf += ";\n\t";
1558 /// if (limit) {
1559 /// unsigned long startMutations = *enumState.mutationsPtr;
1560 /// do {
1561 /// unsigned long counter = 0;
1562 /// do {
1563 /// if (startMutations != *enumState.mutationsPtr)
1564 /// objc_enumerationMutation(l_collection);
1565 /// elem = (type)enumState.itemsPtr[counter++];
1566 buf += "if (limit) {\n\t";
1567 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1568 buf += "do {\n\t\t";
1569 buf += "unsigned long counter = 0;\n\t\t";
1570 buf += "do {\n\t\t\t";
1571 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1572 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1573 buf += elementName;
1574 buf += " = (";
1575 buf += elementTypeAsString;
1576 buf += ")enumState.itemsPtr[counter++];";
1577 // Replace ')' in for '(' type elem in collection ')' with all of these.
1578 ReplaceText(lparenLoc, 1, buf);
1579
1580 /// __continue_label: ;
1581 /// } while (counter < limit);
1582 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1583 /// objects:__rw_items count:16]);
1584 /// elem = nil;
1585 /// __break_label: ;
1586 /// }
1587 /// else
1588 /// elem = nil;
1589 /// }
1590 ///
1591 buf = ";\n\t";
1592 buf += "__continue_label_";
1593 buf += utostr(ObjCBcLabelNo.back());
1594 buf += ": ;";
1595 buf += "\n\t\t";
1596 buf += "} while (counter < limit);\n\t";
1597 buf += "} while (limit = ";
1598 SynthCountByEnumWithState(buf);
1599 buf += ");\n\t";
1600 buf += elementName;
1601 buf += " = ((";
1602 buf += elementTypeAsString;
1603 buf += ")0);\n\t";
1604 buf += "__break_label_";
1605 buf += utostr(ObjCBcLabelNo.back());
1606 buf += ": ;\n\t";
1607 buf += "}\n\t";
1608 buf += "else\n\t\t";
1609 buf += elementName;
1610 buf += " = ((";
1611 buf += elementTypeAsString;
1612 buf += ")0);\n\t";
1613 buf += "}\n";
1614
1615 // Insert all these *after* the statement body.
1616 // FIXME: If this should support Obj-C++, support CXXTryStmt
1617 if (isa<CompoundStmt>(S->getBody())) {
1618 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1619 InsertText(endBodyLoc, buf);
1620 } else {
1621 /* Need to treat single statements specially. For example:
1622 *
1623 * for (A *a in b) if (stuff()) break;
1624 * for (A *a in b) xxxyy;
1625 *
1626 * The following code simply scans ahead to the semi to find the actual end.
1627 */
1628 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1629 const char *semiBuf = strchr(stmtBuf, ';');
1630 assert(semiBuf && "Can't find ';'");
1631 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1632 InsertText(endBodyLoc, buf);
1633 }
1634 Stmts.pop_back();
1635 ObjCBcLabelNo.pop_back();
1636 return 0;
1637}
1638
1639/// RewriteObjCSynchronizedStmt -
1640/// This routine rewrites @synchronized(expr) stmt;
1641/// into:
1642/// objc_sync_enter(expr);
1643/// @try stmt @finally { objc_sync_exit(expr); }
1644///
1645Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1646 // Get the start location and compute the semi location.
1647 SourceLocation startLoc = S->getLocStart();
1648 const char *startBuf = SM->getCharacterData(startLoc);
1649
1650 assert((*startBuf == '@') && "bogus @synchronized location");
1651
1652 std::string buf;
1653 buf = "objc_sync_enter((id)";
1654 const char *lparenBuf = startBuf;
1655 while (*lparenBuf != '(') lparenBuf++;
1656 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1657 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1658 // the sync expression is typically a message expression that's already
1659 // been rewritten! (which implies the SourceLocation's are invalid).
1660 SourceLocation endLoc = S->getSynchBody()->getLocStart();
1661 const char *endBuf = SM->getCharacterData(endLoc);
1662 while (*endBuf != ')') endBuf--;
1663 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1664 buf = ");\n";
1665 // declare a new scope with two variables, _stack and _rethrow.
1666 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1667 buf += "int buf[18/*32-bit i386*/];\n";
1668 buf += "char *pointers[4];} _stack;\n";
1669 buf += "id volatile _rethrow = 0;\n";
1670 buf += "objc_exception_try_enter(&_stack);\n";
1671 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1672 ReplaceText(rparenLoc, 1, buf);
1673 startLoc = S->getSynchBody()->getLocEnd();
1674 startBuf = SM->getCharacterData(startLoc);
1675
1676 assert((*startBuf == '}') && "bogus @synchronized block");
1677 SourceLocation lastCurlyLoc = startLoc;
1678 buf = "}\nelse {\n";
1679 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1680 buf += "}\n";
1681 buf += "{ /* implicit finally clause */\n";
1682 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1683
1684 std::string syncBuf;
1685 syncBuf += " objc_sync_exit(";
1686
1687 Expr *syncExpr = S->getSynchExpr();
1688 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1689 ? CK_BitCast :
1690 syncExpr->getType()->isBlockPointerType()
1691 ? CK_BlockPointerToObjCPointerCast
1692 : CK_CPointerToObjCPointerCast;
1693 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1694 CK, syncExpr);
1695 std::string syncExprBufS;
1696 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1697 syncExpr->printPretty(syncExprBuf, *Context, 0,
1698 PrintingPolicy(LangOpts));
1699 syncBuf += syncExprBuf.str();
1700 syncBuf += ");";
1701
1702 buf += syncBuf;
1703 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
1704 buf += "}\n";
1705 buf += "}";
1706
1707 ReplaceText(lastCurlyLoc, 1, buf);
1708
1709 bool hasReturns = false;
1710 HasReturnStmts(S->getSynchBody(), hasReturns);
1711 if (hasReturns)
1712 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1713
1714 return 0;
1715}
1716
1717void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1718{
1719 // Perform a bottom up traversal of all children.
1720 for (Stmt::child_range CI = S->children(); CI; ++CI)
1721 if (*CI)
1722 WarnAboutReturnGotoStmts(*CI);
1723
1724 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1725 Diags.Report(Context->getFullLoc(S->getLocStart()),
1726 TryFinallyContainsReturnDiag);
1727 }
1728 return;
1729}
1730
1731void RewriteModernObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1732{
1733 // Perform a bottom up traversal of all children.
1734 for (Stmt::child_range CI = S->children(); CI; ++CI)
1735 if (*CI)
1736 HasReturnStmts(*CI, hasReturns);
1737
1738 if (isa<ReturnStmt>(S))
1739 hasReturns = true;
1740 return;
1741}
1742
1743void RewriteModernObjC::RewriteTryReturnStmts(Stmt *S) {
1744 // Perform a bottom up traversal of all children.
1745 for (Stmt::child_range CI = S->children(); CI; ++CI)
1746 if (*CI) {
1747 RewriteTryReturnStmts(*CI);
1748 }
1749 if (isa<ReturnStmt>(S)) {
1750 SourceLocation startLoc = S->getLocStart();
1751 const char *startBuf = SM->getCharacterData(startLoc);
1752
1753 const char *semiBuf = strchr(startBuf, ';');
1754 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1755 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1756
1757 std::string buf;
1758 buf = "{ objc_exception_try_exit(&_stack); return";
1759
1760 ReplaceText(startLoc, 6, buf);
1761 InsertText(onePastSemiLoc, "}");
1762 }
1763 return;
1764}
1765
1766void RewriteModernObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1767 // Perform a bottom up traversal of all children.
1768 for (Stmt::child_range CI = S->children(); CI; ++CI)
1769 if (*CI) {
1770 RewriteSyncReturnStmts(*CI, syncExitBuf);
1771 }
1772 if (isa<ReturnStmt>(S)) {
1773 SourceLocation startLoc = S->getLocStart();
1774 const char *startBuf = SM->getCharacterData(startLoc);
1775
1776 const char *semiBuf = strchr(startBuf, ';');
1777 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1778 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1779
1780 std::string buf;
1781 buf = "{ objc_exception_try_exit(&_stack);";
1782 buf += syncExitBuf;
1783 buf += " return";
1784
1785 ReplaceText(startLoc, 6, buf);
1786 InsertText(onePastSemiLoc, "}");
1787 }
1788 return;
1789}
1790
1791Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1792 // Get the start location and compute the semi location.
1793 SourceLocation startLoc = S->getLocStart();
1794 const char *startBuf = SM->getCharacterData(startLoc);
1795
1796 assert((*startBuf == '@') && "bogus @try location");
1797
1798 std::string buf;
1799 // declare a new scope with two variables, _stack and _rethrow.
1800 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1801 buf += "int buf[18/*32-bit i386*/];\n";
1802 buf += "char *pointers[4];} _stack;\n";
1803 buf += "id volatile _rethrow = 0;\n";
1804 buf += "objc_exception_try_enter(&_stack);\n";
1805 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1806
1807 ReplaceText(startLoc, 4, buf);
1808
1809 startLoc = S->getTryBody()->getLocEnd();
1810 startBuf = SM->getCharacterData(startLoc);
1811
1812 assert((*startBuf == '}') && "bogus @try block");
1813
1814 SourceLocation lastCurlyLoc = startLoc;
1815 if (S->getNumCatchStmts()) {
1816 startLoc = startLoc.getLocWithOffset(1);
1817 buf = " /* @catch begin */ else {\n";
1818 buf += " id _caught = objc_exception_extract(&_stack);\n";
1819 buf += " objc_exception_try_enter (&_stack);\n";
1820 buf += " if (_setjmp(_stack.buf))\n";
1821 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1822 buf += " else { /* @catch continue */";
1823
1824 InsertText(startLoc, buf);
1825 } else { /* no catch list */
1826 buf = "}\nelse {\n";
1827 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1828 buf += "}";
1829 ReplaceText(lastCurlyLoc, 1, buf);
1830 }
1831 Stmt *lastCatchBody = 0;
1832 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1833 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1834 VarDecl *catchDecl = Catch->getCatchParamDecl();
1835
1836 if (I == 0)
1837 buf = "if ("; // we are generating code for the first catch clause
1838 else
1839 buf = "else if (";
1840 startLoc = Catch->getLocStart();
1841 startBuf = SM->getCharacterData(startLoc);
1842
1843 assert((*startBuf == '@') && "bogus @catch location");
1844
1845 const char *lParenLoc = strchr(startBuf, '(');
1846
1847 if (Catch->hasEllipsis()) {
1848 // Now rewrite the body...
1849 lastCatchBody = Catch->getCatchBody();
1850 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1851 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1852 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1853 "bogus @catch paren location");
1854 assert((*bodyBuf == '{') && "bogus @catch body location");
1855
1856 buf += "1) { id _tmp = _caught;";
1857 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1858 } else if (catchDecl) {
1859 QualType t = catchDecl->getType();
1860 if (t == Context->getObjCIdType()) {
1861 buf += "1) { ";
1862 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1863 } else if (const ObjCObjectPointerType *Ptr =
1864 t->getAs<ObjCObjectPointerType>()) {
1865 // Should be a pointer to a class.
1866 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1867 if (IDecl) {
1868 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1869 buf += IDecl->getNameAsString();
1870 buf += "\"), (struct objc_object *)_caught)) { ";
1871 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1872 }
1873 }
1874 // Now rewrite the body...
1875 lastCatchBody = Catch->getCatchBody();
1876 SourceLocation rParenLoc = Catch->getRParenLoc();
1877 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1878 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1879 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1880 assert((*rParenBuf == ')') && "bogus @catch paren location");
1881 assert((*bodyBuf == '{') && "bogus @catch body location");
1882
1883 // Here we replace ") {" with "= _caught;" (which initializes and
1884 // declares the @catch parameter).
1885 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1886 } else {
1887 llvm_unreachable("@catch rewrite bug");
1888 }
1889 }
1890 // Complete the catch list...
1891 if (lastCatchBody) {
1892 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
1893 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1894 "bogus @catch body location");
1895
1896 // Insert the last (implicit) else clause *before* the right curly brace.
1897 bodyLoc = bodyLoc.getLocWithOffset(-1);
1898 buf = "} /* last catch end */\n";
1899 buf += "else {\n";
1900 buf += " _rethrow = _caught;\n";
1901 buf += " objc_exception_try_exit(&_stack);\n";
1902 buf += "} } /* @catch end */\n";
1903 if (!S->getFinallyStmt())
1904 buf += "}\n";
1905 InsertText(bodyLoc, buf);
1906
1907 // Set lastCurlyLoc
1908 lastCurlyLoc = lastCatchBody->getLocEnd();
1909 }
1910 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1911 startLoc = finalStmt->getLocStart();
1912 startBuf = SM->getCharacterData(startLoc);
1913 assert((*startBuf == '@') && "bogus @finally start");
1914
1915 ReplaceText(startLoc, 8, "/* @finally */");
1916
1917 Stmt *body = finalStmt->getFinallyBody();
1918 SourceLocation startLoc = body->getLocStart();
1919 SourceLocation endLoc = body->getLocEnd();
1920 assert(*SM->getCharacterData(startLoc) == '{' &&
1921 "bogus @finally body location");
1922 assert(*SM->getCharacterData(endLoc) == '}' &&
1923 "bogus @finally body location");
1924
1925 startLoc = startLoc.getLocWithOffset(1);
1926 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1927 endLoc = endLoc.getLocWithOffset(-1);
1928 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1929
1930 // Set lastCurlyLoc
1931 lastCurlyLoc = body->getLocEnd();
1932
1933 // Now check for any return/continue/go statements within the @try.
1934 WarnAboutReturnGotoStmts(S->getTryBody());
1935 } else { /* no finally clause - make sure we synthesize an implicit one */
1936 buf = "{ /* implicit finally clause */\n";
1937 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1938 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1939 buf += "}";
1940 ReplaceText(lastCurlyLoc, 1, buf);
1941
1942 // Now check for any return/continue/go statements within the @try.
1943 // The implicit finally clause won't called if the @try contains any
1944 // jump statements.
1945 bool hasReturns = false;
1946 HasReturnStmts(S->getTryBody(), hasReturns);
1947 if (hasReturns)
1948 RewriteTryReturnStmts(S->getTryBody());
1949 }
1950 // Now emit the final closing curly brace...
1951 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1952 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1953 return 0;
1954}
1955
1956// This can't be done with ReplaceStmt(S, ThrowExpr), since
1957// the throw expression is typically a message expression that's already
1958// been rewritten! (which implies the SourceLocation's are invalid).
1959Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1960 // Get the start location and compute the semi location.
1961 SourceLocation startLoc = S->getLocStart();
1962 const char *startBuf = SM->getCharacterData(startLoc);
1963
1964 assert((*startBuf == '@') && "bogus @throw location");
1965
1966 std::string buf;
1967 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1968 if (S->getThrowExpr())
1969 buf = "objc_exception_throw(";
1970 else // add an implicit argument
1971 buf = "objc_exception_throw(_caught";
1972
1973 // handle "@ throw" correctly.
1974 const char *wBuf = strchr(startBuf, 'w');
1975 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1976 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1977
1978 const char *semiBuf = strchr(startBuf, ';');
1979 assert((*semiBuf == ';') && "@throw: can't find ';'");
1980 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1981 ReplaceText(semiLoc, 1, ");");
1982 return 0;
1983}
1984
1985Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1986 // Create a new string expression.
1987 QualType StrType = Context->getPointerType(Context->CharTy);
1988 std::string StrEncoding;
1989 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1990 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1991 StringLiteral::Ascii, false,
1992 StrType, SourceLocation());
1993 ReplaceStmt(Exp, Replacement);
1994
1995 // Replace this subexpr in the parent.
1996 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1997 return Replacement;
1998}
1999
2000Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2001 if (!SelGetUidFunctionDecl)
2002 SynthSelGetUidFunctionDecl();
2003 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2004 // Create a call to sel_registerName("selName").
2005 SmallVector<Expr*, 8> SelExprs;
2006 QualType argType = Context->getPointerType(Context->CharTy);
2007 SelExprs.push_back(StringLiteral::Create(*Context,
2008 Exp->getSelector().getAsString(),
2009 StringLiteral::Ascii, false,
2010 argType, SourceLocation()));
2011 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2012 &SelExprs[0], SelExprs.size());
2013 ReplaceStmt(Exp, SelExp);
2014 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2015 return SelExp;
2016}
2017
2018CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2019 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2020 SourceLocation EndLoc) {
2021 // Get the type, we will need to reference it in a couple spots.
2022 QualType msgSendType = FD->getType();
2023
2024 // Create a reference to the objc_msgSend() declaration.
2025 DeclRefExpr *DRE =
2026 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
2027
2028 // Now, we cast the reference to a pointer to the objc_msgSend type.
2029 QualType pToFunc = Context->getPointerType(msgSendType);
2030 ImplicitCastExpr *ICE =
2031 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2032 DRE, 0, VK_RValue);
2033
2034 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2035
2036 CallExpr *Exp =
2037 new (Context) CallExpr(*Context, ICE, args, nargs,
2038 FT->getCallResultType(*Context),
2039 VK_RValue, EndLoc);
2040 return Exp;
2041}
2042
2043static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2044 const char *&startRef, const char *&endRef) {
2045 while (startBuf < endBuf) {
2046 if (*startBuf == '<')
2047 startRef = startBuf; // mark the start.
2048 if (*startBuf == '>') {
2049 if (startRef && *startRef == '<') {
2050 endRef = startBuf; // mark the end.
2051 return true;
2052 }
2053 return false;
2054 }
2055 startBuf++;
2056 }
2057 return false;
2058}
2059
2060static void scanToNextArgument(const char *&argRef) {
2061 int angle = 0;
2062 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2063 if (*argRef == '<')
2064 angle++;
2065 else if (*argRef == '>')
2066 angle--;
2067 argRef++;
2068 }
2069 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2070}
2071
2072bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2073 if (T->isObjCQualifiedIdType())
2074 return true;
2075 if (const PointerType *PT = T->getAs<PointerType>()) {
2076 if (PT->getPointeeType()->isObjCQualifiedIdType())
2077 return true;
2078 }
2079 if (T->isObjCObjectPointerType()) {
2080 T = T->getPointeeType();
2081 return T->isObjCQualifiedInterfaceType();
2082 }
2083 if (T->isArrayType()) {
2084 QualType ElemTy = Context->getBaseElementType(T);
2085 return needToScanForQualifiers(ElemTy);
2086 }
2087 return false;
2088}
2089
2090void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2091 QualType Type = E->getType();
2092 if (needToScanForQualifiers(Type)) {
2093 SourceLocation Loc, EndLoc;
2094
2095 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2096 Loc = ECE->getLParenLoc();
2097 EndLoc = ECE->getRParenLoc();
2098 } else {
2099 Loc = E->getLocStart();
2100 EndLoc = E->getLocEnd();
2101 }
2102 // This will defend against trying to rewrite synthesized expressions.
2103 if (Loc.isInvalid() || EndLoc.isInvalid())
2104 return;
2105
2106 const char *startBuf = SM->getCharacterData(Loc);
2107 const char *endBuf = SM->getCharacterData(EndLoc);
2108 const char *startRef = 0, *endRef = 0;
2109 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2110 // Get the locations of the startRef, endRef.
2111 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2112 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2113 // Comment out the protocol references.
2114 InsertText(LessLoc, "/*");
2115 InsertText(GreaterLoc, "*/");
2116 }
2117 }
2118}
2119
2120void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2121 SourceLocation Loc;
2122 QualType Type;
2123 const FunctionProtoType *proto = 0;
2124 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2125 Loc = VD->getLocation();
2126 Type = VD->getType();
2127 }
2128 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2129 Loc = FD->getLocation();
2130 // Check for ObjC 'id' and class types that have been adorned with protocol
2131 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2132 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2133 assert(funcType && "missing function type");
2134 proto = dyn_cast<FunctionProtoType>(funcType);
2135 if (!proto)
2136 return;
2137 Type = proto->getResultType();
2138 }
2139 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2140 Loc = FD->getLocation();
2141 Type = FD->getType();
2142 }
2143 else
2144 return;
2145
2146 if (needToScanForQualifiers(Type)) {
2147 // Since types are unique, we need to scan the buffer.
2148
2149 const char *endBuf = SM->getCharacterData(Loc);
2150 const char *startBuf = endBuf;
2151 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2152 startBuf--; // scan backward (from the decl location) for return type.
2153 const char *startRef = 0, *endRef = 0;
2154 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2155 // Get the locations of the startRef, endRef.
2156 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2157 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2158 // Comment out the protocol references.
2159 InsertText(LessLoc, "/*");
2160 InsertText(GreaterLoc, "*/");
2161 }
2162 }
2163 if (!proto)
2164 return; // most likely, was a variable
2165 // Now check arguments.
2166 const char *startBuf = SM->getCharacterData(Loc);
2167 const char *startFuncBuf = startBuf;
2168 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2169 if (needToScanForQualifiers(proto->getArgType(i))) {
2170 // Since types are unique, we need to scan the buffer.
2171
2172 const char *endBuf = startBuf;
2173 // scan forward (from the decl location) for argument types.
2174 scanToNextArgument(endBuf);
2175 const char *startRef = 0, *endRef = 0;
2176 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2177 // Get the locations of the startRef, endRef.
2178 SourceLocation LessLoc =
2179 Loc.getLocWithOffset(startRef-startFuncBuf);
2180 SourceLocation GreaterLoc =
2181 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2182 // Comment out the protocol references.
2183 InsertText(LessLoc, "/*");
2184 InsertText(GreaterLoc, "*/");
2185 }
2186 startBuf = ++endBuf;
2187 }
2188 else {
2189 // If the function name is derived from a macro expansion, then the
2190 // argument buffer will not follow the name. Need to speak with Chris.
2191 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2192 startBuf++; // scan forward (from the decl location) for argument types.
2193 startBuf++;
2194 }
2195 }
2196}
2197
2198void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2199 QualType QT = ND->getType();
2200 const Type* TypePtr = QT->getAs<Type>();
2201 if (!isa<TypeOfExprType>(TypePtr))
2202 return;
2203 while (isa<TypeOfExprType>(TypePtr)) {
2204 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2205 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2206 TypePtr = QT->getAs<Type>();
2207 }
2208 // FIXME. This will not work for multiple declarators; as in:
2209 // __typeof__(a) b,c,d;
2210 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2211 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2212 const char *startBuf = SM->getCharacterData(DeclLoc);
2213 if (ND->getInit()) {
2214 std::string Name(ND->getNameAsString());
2215 TypeAsString += " " + Name + " = ";
2216 Expr *E = ND->getInit();
2217 SourceLocation startLoc;
2218 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2219 startLoc = ECE->getLParenLoc();
2220 else
2221 startLoc = E->getLocStart();
2222 startLoc = SM->getExpansionLoc(startLoc);
2223 const char *endBuf = SM->getCharacterData(startLoc);
2224 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2225 }
2226 else {
2227 SourceLocation X = ND->getLocEnd();
2228 X = SM->getExpansionLoc(X);
2229 const char *endBuf = SM->getCharacterData(X);
2230 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2231 }
2232}
2233
2234// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2235void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2236 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2237 SmallVector<QualType, 16> ArgTys;
2238 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2239 QualType getFuncType =
2240 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2241 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2242 SourceLocation(),
2243 SourceLocation(),
2244 SelGetUidIdent, getFuncType, 0,
2245 SC_Extern,
2246 SC_None, false);
2247}
2248
2249void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2250 // declared in <objc/objc.h>
2251 if (FD->getIdentifier() &&
2252 FD->getName() == "sel_registerName") {
2253 SelGetUidFunctionDecl = FD;
2254 return;
2255 }
2256 RewriteObjCQualifiedInterfaceTypes(FD);
2257}
2258
2259void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2260 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2261 const char *argPtr = TypeString.c_str();
2262 if (!strchr(argPtr, '^')) {
2263 Str += TypeString;
2264 return;
2265 }
2266 while (*argPtr) {
2267 Str += (*argPtr == '^' ? '*' : *argPtr);
2268 argPtr++;
2269 }
2270}
2271
2272// FIXME. Consolidate this routine with RewriteBlockPointerType.
2273void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2274 ValueDecl *VD) {
2275 QualType Type = VD->getType();
2276 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2277 const char *argPtr = TypeString.c_str();
2278 int paren = 0;
2279 while (*argPtr) {
2280 switch (*argPtr) {
2281 case '(':
2282 Str += *argPtr;
2283 paren++;
2284 break;
2285 case ')':
2286 Str += *argPtr;
2287 paren--;
2288 break;
2289 case '^':
2290 Str += '*';
2291 if (paren == 1)
2292 Str += VD->getNameAsString();
2293 break;
2294 default:
2295 Str += *argPtr;
2296 break;
2297 }
2298 argPtr++;
2299 }
2300}
2301
2302
2303void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2304 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2305 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2306 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2307 if (!proto)
2308 return;
2309 QualType Type = proto->getResultType();
2310 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2311 FdStr += " ";
2312 FdStr += FD->getName();
2313 FdStr += "(";
2314 unsigned numArgs = proto->getNumArgs();
2315 for (unsigned i = 0; i < numArgs; i++) {
2316 QualType ArgType = proto->getArgType(i);
2317 RewriteBlockPointerType(FdStr, ArgType);
2318 if (i+1 < numArgs)
2319 FdStr += ", ";
2320 }
2321 FdStr += ");\n";
2322 InsertText(FunLocStart, FdStr);
2323 CurFunctionDeclToDeclareForBlock = 0;
2324}
2325
2326// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2327void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2328 if (SuperContructorFunctionDecl)
2329 return;
2330 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2331 SmallVector<QualType, 16> ArgTys;
2332 QualType argT = Context->getObjCIdType();
2333 assert(!argT.isNull() && "Can't find 'id' type");
2334 ArgTys.push_back(argT);
2335 ArgTys.push_back(argT);
2336 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2337 &ArgTys[0], ArgTys.size());
2338 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2339 SourceLocation(),
2340 SourceLocation(),
2341 msgSendIdent, msgSendType, 0,
2342 SC_Extern,
2343 SC_None, false);
2344}
2345
2346// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2347void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2348 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2349 SmallVector<QualType, 16> ArgTys;
2350 QualType argT = Context->getObjCIdType();
2351 assert(!argT.isNull() && "Can't find 'id' type");
2352 ArgTys.push_back(argT);
2353 argT = Context->getObjCSelType();
2354 assert(!argT.isNull() && "Can't find 'SEL' type");
2355 ArgTys.push_back(argT);
2356 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2357 &ArgTys[0], ArgTys.size(),
2358 true /*isVariadic*/);
2359 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2360 SourceLocation(),
2361 SourceLocation(),
2362 msgSendIdent, msgSendType, 0,
2363 SC_Extern,
2364 SC_None, false);
2365}
2366
2367// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2368void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2369 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2370 SmallVector<QualType, 16> ArgTys;
2371 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2372 SourceLocation(), SourceLocation(),
2373 &Context->Idents.get("objc_super"));
2374 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2375 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2376 ArgTys.push_back(argT);
2377 argT = Context->getObjCSelType();
2378 assert(!argT.isNull() && "Can't find 'SEL' type");
2379 ArgTys.push_back(argT);
2380 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2381 &ArgTys[0], ArgTys.size(),
2382 true /*isVariadic*/);
2383 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2384 SourceLocation(),
2385 SourceLocation(),
2386 msgSendIdent, msgSendType, 0,
2387 SC_Extern,
2388 SC_None, false);
2389}
2390
2391// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2392void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2393 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2394 SmallVector<QualType, 16> ArgTys;
2395 QualType argT = Context->getObjCIdType();
2396 assert(!argT.isNull() && "Can't find 'id' type");
2397 ArgTys.push_back(argT);
2398 argT = Context->getObjCSelType();
2399 assert(!argT.isNull() && "Can't find 'SEL' type");
2400 ArgTys.push_back(argT);
2401 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2402 &ArgTys[0], ArgTys.size(),
2403 true /*isVariadic*/);
2404 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2405 SourceLocation(),
2406 SourceLocation(),
2407 msgSendIdent, msgSendType, 0,
2408 SC_Extern,
2409 SC_None, false);
2410}
2411
2412// SynthMsgSendSuperStretFunctionDecl -
2413// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2414void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2415 IdentifierInfo *msgSendIdent =
2416 &Context->Idents.get("objc_msgSendSuper_stret");
2417 SmallVector<QualType, 16> ArgTys;
2418 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2419 SourceLocation(), SourceLocation(),
2420 &Context->Idents.get("objc_super"));
2421 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2422 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2423 ArgTys.push_back(argT);
2424 argT = Context->getObjCSelType();
2425 assert(!argT.isNull() && "Can't find 'SEL' type");
2426 ArgTys.push_back(argT);
2427 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2428 &ArgTys[0], ArgTys.size(),
2429 true /*isVariadic*/);
2430 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2431 SourceLocation(),
2432 SourceLocation(),
2433 msgSendIdent, msgSendType, 0,
2434 SC_Extern,
2435 SC_None, false);
2436}
2437
2438// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2439void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2440 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2441 SmallVector<QualType, 16> ArgTys;
2442 QualType argT = Context->getObjCIdType();
2443 assert(!argT.isNull() && "Can't find 'id' type");
2444 ArgTys.push_back(argT);
2445 argT = Context->getObjCSelType();
2446 assert(!argT.isNull() && "Can't find 'SEL' type");
2447 ArgTys.push_back(argT);
2448 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2449 &ArgTys[0], ArgTys.size(),
2450 true /*isVariadic*/);
2451 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2452 SourceLocation(),
2453 SourceLocation(),
2454 msgSendIdent, msgSendType, 0,
2455 SC_Extern,
2456 SC_None, false);
2457}
2458
2459// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2460void RewriteModernObjC::SynthGetClassFunctionDecl() {
2461 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2462 SmallVector<QualType, 16> ArgTys;
2463 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2464 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2465 &ArgTys[0], ArgTys.size());
2466 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2467 SourceLocation(),
2468 SourceLocation(),
2469 getClassIdent, getClassType, 0,
2470 SC_Extern,
2471 SC_None, false);
2472}
2473
2474// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2475void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2476 IdentifierInfo *getSuperClassIdent =
2477 &Context->Idents.get("class_getSuperclass");
2478 SmallVector<QualType, 16> ArgTys;
2479 ArgTys.push_back(Context->getObjCClassType());
2480 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2481 &ArgTys[0], ArgTys.size());
2482 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2483 SourceLocation(),
2484 SourceLocation(),
2485 getSuperClassIdent,
2486 getClassType, 0,
2487 SC_Extern,
2488 SC_None,
2489 false);
2490}
2491
2492// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2493void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2494 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2495 SmallVector<QualType, 16> ArgTys;
2496 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2497 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2498 &ArgTys[0], ArgTys.size());
2499 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2500 SourceLocation(),
2501 SourceLocation(),
2502 getClassIdent, getClassType, 0,
2503 SC_Extern,
2504 SC_None, false);
2505}
2506
2507Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2508 QualType strType = getConstantStringStructType();
2509
2510 std::string S = "__NSConstantStringImpl_";
2511
2512 std::string tmpName = InFileName;
2513 unsigned i;
2514 for (i=0; i < tmpName.length(); i++) {
2515 char c = tmpName.at(i);
2516 // replace any non alphanumeric characters with '_'.
2517 if (!isalpha(c) && (c < '0' || c > '9'))
2518 tmpName[i] = '_';
2519 }
2520 S += tmpName;
2521 S += "_";
2522 S += utostr(NumObjCStringLiterals++);
2523
2524 Preamble += "static __NSConstantStringImpl " + S;
2525 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2526 Preamble += "0x000007c8,"; // utf8_str
2527 // The pretty printer for StringLiteral handles escape characters properly.
2528 std::string prettyBufS;
2529 llvm::raw_string_ostream prettyBuf(prettyBufS);
2530 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2531 PrintingPolicy(LangOpts));
2532 Preamble += prettyBuf.str();
2533 Preamble += ",";
2534 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2535
2536 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2537 SourceLocation(), &Context->Idents.get(S),
2538 strType, 0, SC_Static, SC_None);
2539 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2540 SourceLocation());
2541 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2542 Context->getPointerType(DRE->getType()),
2543 VK_RValue, OK_Ordinary,
2544 SourceLocation());
2545 // cast to NSConstantString *
2546 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2547 CK_CPointerToObjCPointerCast, Unop);
2548 ReplaceStmt(Exp, cast);
2549 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2550 return cast;
2551}
2552
2553// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2554QualType RewriteModernObjC::getSuperStructType() {
2555 if (!SuperStructDecl) {
2556 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2557 SourceLocation(), SourceLocation(),
2558 &Context->Idents.get("objc_super"));
2559 QualType FieldTypes[2];
2560
2561 // struct objc_object *receiver;
2562 FieldTypes[0] = Context->getObjCIdType();
2563 // struct objc_class *super;
2564 FieldTypes[1] = Context->getObjCClassType();
2565
2566 // Create fields
2567 for (unsigned i = 0; i < 2; ++i) {
2568 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2569 SourceLocation(),
2570 SourceLocation(), 0,
2571 FieldTypes[i], 0,
2572 /*BitWidth=*/0,
2573 /*Mutable=*/false,
2574 /*HasInit=*/false));
2575 }
2576
2577 SuperStructDecl->completeDefinition();
2578 }
2579 return Context->getTagDeclType(SuperStructDecl);
2580}
2581
2582QualType RewriteModernObjC::getConstantStringStructType() {
2583 if (!ConstantStringDecl) {
2584 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2585 SourceLocation(), SourceLocation(),
2586 &Context->Idents.get("__NSConstantStringImpl"));
2587 QualType FieldTypes[4];
2588
2589 // struct objc_object *receiver;
2590 FieldTypes[0] = Context->getObjCIdType();
2591 // int flags;
2592 FieldTypes[1] = Context->IntTy;
2593 // char *str;
2594 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2595 // long length;
2596 FieldTypes[3] = Context->LongTy;
2597
2598 // Create fields
2599 for (unsigned i = 0; i < 4; ++i) {
2600 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2601 ConstantStringDecl,
2602 SourceLocation(),
2603 SourceLocation(), 0,
2604 FieldTypes[i], 0,
2605 /*BitWidth=*/0,
2606 /*Mutable=*/true,
2607 /*HasInit=*/false));
2608 }
2609
2610 ConstantStringDecl->completeDefinition();
2611 }
2612 return Context->getTagDeclType(ConstantStringDecl);
2613}
2614
2615Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2616 SourceLocation StartLoc,
2617 SourceLocation EndLoc) {
2618 if (!SelGetUidFunctionDecl)
2619 SynthSelGetUidFunctionDecl();
2620 if (!MsgSendFunctionDecl)
2621 SynthMsgSendFunctionDecl();
2622 if (!MsgSendSuperFunctionDecl)
2623 SynthMsgSendSuperFunctionDecl();
2624 if (!MsgSendStretFunctionDecl)
2625 SynthMsgSendStretFunctionDecl();
2626 if (!MsgSendSuperStretFunctionDecl)
2627 SynthMsgSendSuperStretFunctionDecl();
2628 if (!MsgSendFpretFunctionDecl)
2629 SynthMsgSendFpretFunctionDecl();
2630 if (!GetClassFunctionDecl)
2631 SynthGetClassFunctionDecl();
2632 if (!GetSuperClassFunctionDecl)
2633 SynthGetSuperClassFunctionDecl();
2634 if (!GetMetaClassFunctionDecl)
2635 SynthGetMetaClassFunctionDecl();
2636
2637 // default to objc_msgSend().
2638 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2639 // May need to use objc_msgSend_stret() as well.
2640 FunctionDecl *MsgSendStretFlavor = 0;
2641 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2642 QualType resultType = mDecl->getResultType();
2643 if (resultType->isRecordType())
2644 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2645 else if (resultType->isRealFloatingType())
2646 MsgSendFlavor = MsgSendFpretFunctionDecl;
2647 }
2648
2649 // Synthesize a call to objc_msgSend().
2650 SmallVector<Expr*, 8> MsgExprs;
2651 switch (Exp->getReceiverKind()) {
2652 case ObjCMessageExpr::SuperClass: {
2653 MsgSendFlavor = MsgSendSuperFunctionDecl;
2654 if (MsgSendStretFlavor)
2655 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2656 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2657
2658 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2659
2660 SmallVector<Expr*, 4> InitExprs;
2661
2662 // set the receiver to self, the first argument to all methods.
2663 InitExprs.push_back(
2664 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2665 CK_BitCast,
2666 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2667 Context->getObjCIdType(),
2668 VK_RValue,
2669 SourceLocation()))
2670 ); // set the 'receiver'.
2671
2672 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2673 SmallVector<Expr*, 8> ClsExprs;
2674 QualType argType = Context->getPointerType(Context->CharTy);
2675 ClsExprs.push_back(StringLiteral::Create(*Context,
2676 ClassDecl->getIdentifier()->getName(),
2677 StringLiteral::Ascii, false,
2678 argType, SourceLocation()));
2679 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2680 &ClsExprs[0],
2681 ClsExprs.size(),
2682 StartLoc,
2683 EndLoc);
2684 // (Class)objc_getClass("CurrentClass")
2685 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2686 Context->getObjCClassType(),
2687 CK_BitCast, Cls);
2688 ClsExprs.clear();
2689 ClsExprs.push_back(ArgExpr);
2690 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2691 &ClsExprs[0], ClsExprs.size(),
2692 StartLoc, EndLoc);
2693
2694 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2695 // To turn off a warning, type-cast to 'id'
2696 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2697 NoTypeInfoCStyleCastExpr(Context,
2698 Context->getObjCIdType(),
2699 CK_BitCast, Cls));
2700 // struct objc_super
2701 QualType superType = getSuperStructType();
2702 Expr *SuperRep;
2703
2704 if (LangOpts.MicrosoftExt) {
2705 SynthSuperContructorFunctionDecl();
2706 // Simulate a contructor call...
2707 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2708 superType, VK_LValue,
2709 SourceLocation());
2710 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2711 InitExprs.size(),
2712 superType, VK_LValue,
2713 SourceLocation());
2714 // The code for super is a little tricky to prevent collision with
2715 // the structure definition in the header. The rewriter has it's own
2716 // internal definition (__rw_objc_super) that is uses. This is why
2717 // we need the cast below. For example:
2718 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2719 //
2720 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2721 Context->getPointerType(SuperRep->getType()),
2722 VK_RValue, OK_Ordinary,
2723 SourceLocation());
2724 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2725 Context->getPointerType(superType),
2726 CK_BitCast, SuperRep);
2727 } else {
2728 // (struct objc_super) { <exprs from above> }
2729 InitListExpr *ILE =
2730 new (Context) InitListExpr(*Context, SourceLocation(),
2731 &InitExprs[0], InitExprs.size(),
2732 SourceLocation());
2733 TypeSourceInfo *superTInfo
2734 = Context->getTrivialTypeSourceInfo(superType);
2735 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2736 superType, VK_LValue,
2737 ILE, false);
2738 // struct objc_super *
2739 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2740 Context->getPointerType(SuperRep->getType()),
2741 VK_RValue, OK_Ordinary,
2742 SourceLocation());
2743 }
2744 MsgExprs.push_back(SuperRep);
2745 break;
2746 }
2747
2748 case ObjCMessageExpr::Class: {
2749 SmallVector<Expr*, 8> ClsExprs;
2750 QualType argType = Context->getPointerType(Context->CharTy);
2751 ObjCInterfaceDecl *Class
2752 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2753 IdentifierInfo *clsName = Class->getIdentifier();
2754 ClsExprs.push_back(StringLiteral::Create(*Context,
2755 clsName->getName(),
2756 StringLiteral::Ascii, false,
2757 argType, SourceLocation()));
2758 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2759 &ClsExprs[0],
2760 ClsExprs.size(),
2761 StartLoc, EndLoc);
2762 MsgExprs.push_back(Cls);
2763 break;
2764 }
2765
2766 case ObjCMessageExpr::SuperInstance:{
2767 MsgSendFlavor = MsgSendSuperFunctionDecl;
2768 if (MsgSendStretFlavor)
2769 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2770 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2771 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2772 SmallVector<Expr*, 4> InitExprs;
2773
2774 InitExprs.push_back(
2775 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2776 CK_BitCast,
2777 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
2778 Context->getObjCIdType(),
2779 VK_RValue, SourceLocation()))
2780 ); // set the 'receiver'.
2781
2782 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2783 SmallVector<Expr*, 8> ClsExprs;
2784 QualType argType = Context->getPointerType(Context->CharTy);
2785 ClsExprs.push_back(StringLiteral::Create(*Context,
2786 ClassDecl->getIdentifier()->getName(),
2787 StringLiteral::Ascii, false, argType,
2788 SourceLocation()));
2789 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2790 &ClsExprs[0],
2791 ClsExprs.size(),
2792 StartLoc, EndLoc);
2793 // (Class)objc_getClass("CurrentClass")
2794 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2795 Context->getObjCClassType(),
2796 CK_BitCast, Cls);
2797 ClsExprs.clear();
2798 ClsExprs.push_back(ArgExpr);
2799 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2800 &ClsExprs[0], ClsExprs.size(),
2801 StartLoc, EndLoc);
2802
2803 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2804 // To turn off a warning, type-cast to 'id'
2805 InitExprs.push_back(
2806 // set 'super class', using class_getSuperclass().
2807 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2808 CK_BitCast, Cls));
2809 // struct objc_super
2810 QualType superType = getSuperStructType();
2811 Expr *SuperRep;
2812
2813 if (LangOpts.MicrosoftExt) {
2814 SynthSuperContructorFunctionDecl();
2815 // Simulate a contructor call...
2816 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
2817 superType, VK_LValue,
2818 SourceLocation());
2819 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2820 InitExprs.size(),
2821 superType, VK_LValue, SourceLocation());
2822 // The code for super is a little tricky to prevent collision with
2823 // the structure definition in the header. The rewriter has it's own
2824 // internal definition (__rw_objc_super) that is uses. This is why
2825 // we need the cast below. For example:
2826 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2827 //
2828 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2829 Context->getPointerType(SuperRep->getType()),
2830 VK_RValue, OK_Ordinary,
2831 SourceLocation());
2832 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2833 Context->getPointerType(superType),
2834 CK_BitCast, SuperRep);
2835 } else {
2836 // (struct objc_super) { <exprs from above> }
2837 InitListExpr *ILE =
2838 new (Context) InitListExpr(*Context, SourceLocation(),
2839 &InitExprs[0], InitExprs.size(),
2840 SourceLocation());
2841 TypeSourceInfo *superTInfo
2842 = Context->getTrivialTypeSourceInfo(superType);
2843 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2844 superType, VK_RValue, ILE,
2845 false);
2846 }
2847 MsgExprs.push_back(SuperRep);
2848 break;
2849 }
2850
2851 case ObjCMessageExpr::Instance: {
2852 // Remove all type-casts because it may contain objc-style types; e.g.
2853 // Foo<Proto> *.
2854 Expr *recExpr = Exp->getInstanceReceiver();
2855 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2856 recExpr = CE->getSubExpr();
2857 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2858 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2859 ? CK_BlockPointerToObjCPointerCast
2860 : CK_CPointerToObjCPointerCast;
2861
2862 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2863 CK, recExpr);
2864 MsgExprs.push_back(recExpr);
2865 break;
2866 }
2867 }
2868
2869 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2870 SmallVector<Expr*, 8> SelExprs;
2871 QualType argType = Context->getPointerType(Context->CharTy);
2872 SelExprs.push_back(StringLiteral::Create(*Context,
2873 Exp->getSelector().getAsString(),
2874 StringLiteral::Ascii, false,
2875 argType, SourceLocation()));
2876 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2877 &SelExprs[0], SelExprs.size(),
2878 StartLoc,
2879 EndLoc);
2880 MsgExprs.push_back(SelExp);
2881
2882 // Now push any user supplied arguments.
2883 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2884 Expr *userExpr = Exp->getArg(i);
2885 // Make all implicit casts explicit...ICE comes in handy:-)
2886 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2887 // Reuse the ICE type, it is exactly what the doctor ordered.
2888 QualType type = ICE->getType();
2889 if (needToScanForQualifiers(type))
2890 type = Context->getObjCIdType();
2891 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2892 (void)convertBlockPointerToFunctionPointer(type);
2893 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2894 CastKind CK;
2895 if (SubExpr->getType()->isIntegralType(*Context) &&
2896 type->isBooleanType()) {
2897 CK = CK_IntegralToBoolean;
2898 } else if (type->isObjCObjectPointerType()) {
2899 if (SubExpr->getType()->isBlockPointerType()) {
2900 CK = CK_BlockPointerToObjCPointerCast;
2901 } else if (SubExpr->getType()->isPointerType()) {
2902 CK = CK_CPointerToObjCPointerCast;
2903 } else {
2904 CK = CK_BitCast;
2905 }
2906 } else {
2907 CK = CK_BitCast;
2908 }
2909
2910 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2911 }
2912 // Make id<P...> cast into an 'id' cast.
2913 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2914 if (CE->getType()->isObjCQualifiedIdType()) {
2915 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2916 userExpr = CE->getSubExpr();
2917 CastKind CK;
2918 if (userExpr->getType()->isIntegralType(*Context)) {
2919 CK = CK_IntegralToPointer;
2920 } else if (userExpr->getType()->isBlockPointerType()) {
2921 CK = CK_BlockPointerToObjCPointerCast;
2922 } else if (userExpr->getType()->isPointerType()) {
2923 CK = CK_CPointerToObjCPointerCast;
2924 } else {
2925 CK = CK_BitCast;
2926 }
2927 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2928 CK, userExpr);
2929 }
2930 }
2931 MsgExprs.push_back(userExpr);
2932 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2933 // out the argument in the original expression (since we aren't deleting
2934 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2935 //Exp->setArg(i, 0);
2936 }
2937 // Generate the funky cast.
2938 CastExpr *cast;
2939 SmallVector<QualType, 8> ArgTypes;
2940 QualType returnType;
2941
2942 // Push 'id' and 'SEL', the 2 implicit arguments.
2943 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2944 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2945 else
2946 ArgTypes.push_back(Context->getObjCIdType());
2947 ArgTypes.push_back(Context->getObjCSelType());
2948 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2949 // Push any user argument types.
2950 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2951 E = OMD->param_end(); PI != E; ++PI) {
2952 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2953 ? Context->getObjCIdType()
2954 : (*PI)->getType();
2955 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2956 (void)convertBlockPointerToFunctionPointer(t);
2957 ArgTypes.push_back(t);
2958 }
2959 returnType = Exp->getType();
2960 convertToUnqualifiedObjCType(returnType);
2961 (void)convertBlockPointerToFunctionPointer(returnType);
2962 } else {
2963 returnType = Context->getObjCIdType();
2964 }
2965 // Get the type, we will need to reference it in a couple spots.
2966 QualType msgSendType = MsgSendFlavor->getType();
2967
2968 // Create a reference to the objc_msgSend() declaration.
2969 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
2970 VK_LValue, SourceLocation());
2971
2972 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2973 // If we don't do this cast, we get the following bizarre warning/note:
2974 // xx.m:13: warning: function called through a non-compatible type
2975 // xx.m:13: note: if this code is reached, the program will abort
2976 cast = NoTypeInfoCStyleCastExpr(Context,
2977 Context->getPointerType(Context->VoidTy),
2978 CK_BitCast, DRE);
2979
2980 // Now do the "normal" pointer to function cast.
2981 QualType castType =
2982 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2983 // If we don't have a method decl, force a variadic cast.
2984 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2985 castType = Context->getPointerType(castType);
2986 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2987 cast);
2988
2989 // Don't forget the parens to enforce the proper binding.
2990 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2991
2992 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2993 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2994 MsgExprs.size(),
2995 FT->getResultType(), VK_RValue,
2996 EndLoc);
2997 Stmt *ReplacingStmt = CE;
2998 if (MsgSendStretFlavor) {
2999 // We have the method which returns a struct/union. Must also generate
3000 // call to objc_msgSend_stret and hang both varieties on a conditional
3001 // expression which dictate which one to envoke depending on size of
3002 // method's return type.
3003
3004 // Create a reference to the objc_msgSend_stret() declaration.
3005 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
3006 VK_LValue, SourceLocation());
3007 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3008 cast = NoTypeInfoCStyleCastExpr(Context,
3009 Context->getPointerType(Context->VoidTy),
3010 CK_BitCast, STDRE);
3011 // Now do the "normal" pointer to function cast.
3012 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3013 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3014 castType = Context->getPointerType(castType);
3015 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3016 cast);
3017
3018 // Don't forget the parens to enforce the proper binding.
3019 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3020
3021 FT = msgSendType->getAs<FunctionType>();
3022 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3023 MsgExprs.size(),
3024 FT->getResultType(), VK_RValue,
3025 SourceLocation());
3026
3027 // Build sizeof(returnType)
3028 UnaryExprOrTypeTraitExpr *sizeofExpr =
3029 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3030 Context->getTrivialTypeSourceInfo(returnType),
3031 Context->getSizeType(), SourceLocation(),
3032 SourceLocation());
3033 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3034 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3035 // For X86 it is more complicated and some kind of target specific routine
3036 // is needed to decide what to do.
3037 unsigned IntSize =
3038 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3039 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3040 llvm::APInt(IntSize, 8),
3041 Context->IntTy,
3042 SourceLocation());
3043 BinaryOperator *lessThanExpr =
3044 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3045 VK_RValue, OK_Ordinary, SourceLocation());
3046 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3047 ConditionalOperator *CondExpr =
3048 new (Context) ConditionalOperator(lessThanExpr,
3049 SourceLocation(), CE,
3050 SourceLocation(), STCE,
3051 returnType, VK_RValue, OK_Ordinary);
3052 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3053 CondExpr);
3054 }
3055 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3056 return ReplacingStmt;
3057}
3058
3059Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3060 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3061 Exp->getLocEnd());
3062
3063 // Now do the actual rewrite.
3064 ReplaceStmt(Exp, ReplacingStmt);
3065
3066 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3067 return ReplacingStmt;
3068}
3069
3070// typedef struct objc_object Protocol;
3071QualType RewriteModernObjC::getProtocolType() {
3072 if (!ProtocolTypeDecl) {
3073 TypeSourceInfo *TInfo
3074 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3075 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3076 SourceLocation(), SourceLocation(),
3077 &Context->Idents.get("Protocol"),
3078 TInfo);
3079 }
3080 return Context->getTypeDeclType(ProtocolTypeDecl);
3081}
3082
3083/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3084/// a synthesized/forward data reference (to the protocol's metadata).
3085/// The forward references (and metadata) are generated in
3086/// RewriteModernObjC::HandleTranslationUnit().
3087Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3088 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3089 IdentifierInfo *ID = &Context->Idents.get(Name);
3090 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3091 SourceLocation(), ID, getProtocolType(), 0,
3092 SC_Extern, SC_None);
3093 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3094 SourceLocation());
3095 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3096 Context->getPointerType(DRE->getType()),
3097 VK_RValue, OK_Ordinary, SourceLocation());
3098 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3099 CK_BitCast,
3100 DerefExpr);
3101 ReplaceStmt(Exp, castExpr);
3102 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3103 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3104 return castExpr;
3105
3106}
3107
3108bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3109 const char *endBuf) {
3110 while (startBuf < endBuf) {
3111 if (*startBuf == '#') {
3112 // Skip whitespace.
3113 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3114 ;
3115 if (!strncmp(startBuf, "if", strlen("if")) ||
3116 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3117 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3118 !strncmp(startBuf, "define", strlen("define")) ||
3119 !strncmp(startBuf, "undef", strlen("undef")) ||
3120 !strncmp(startBuf, "else", strlen("else")) ||
3121 !strncmp(startBuf, "elif", strlen("elif")) ||
3122 !strncmp(startBuf, "endif", strlen("endif")) ||
3123 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3124 !strncmp(startBuf, "include", strlen("include")) ||
3125 !strncmp(startBuf, "import", strlen("import")) ||
3126 !strncmp(startBuf, "include_next", strlen("include_next")))
3127 return true;
3128 }
3129 startBuf++;
3130 }
3131 return false;
3132}
3133
3134/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3135/// an objective-c class with ivars.
3136void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3137 std::string &Result) {
3138 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3139 assert(CDecl->getName() != "" &&
3140 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003141 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003142 SmallVector<ObjCIvarDecl *, 8> IVars;
3143 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3144 IVD; IVD = IVD->getNextIvar()) {
3145 // Ignore unnamed bit-fields.
3146 if (!IVD->getDeclName())
3147 continue;
3148 IVars.push_back(IVD);
3149 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003150 SourceLocation LocStart = CDecl->getLocStart();
3151 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003152
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003153 const char *startBuf = SM->getCharacterData(LocStart);
3154 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003155
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003156 // If no ivars and no root or if its root, directly or indirectly,
3157 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003158 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003159 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3160 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3161 ReplaceText(LocStart, endBuf-startBuf, Result);
3162 return;
3163 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003164
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003165 Result += "\nstruct ";
3166 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003167 Result += "_IMPL {\n";
3168
3169 if (RCDecl) {
3170 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3171 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3172 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003173 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003174
3175 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
3176 ObjCIvarDecl *IvarDecl = IVars[i];
3177 QualType Type = IvarDecl->getType();
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003178 std::string Name = IvarDecl->getNameAsString();
3179
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003180 Result += "\t";
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003181 convertObjCTypeToCStyleType(Type);
3182
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003183 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3184 Result += Name;
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003185 if (IvarDecl->isBitField()) {
3186 Result += " : "; Result += utostr(IvarDecl->getBitWidthValue(*Context));
3187 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003188 Result += ";\n";
3189 }
3190 Result += "};\n";
3191 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3192 ReplaceText(LocStart, endBuf-startBuf, Result);
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
3222 for (int i = 0; i < CatDefCount; i++)
3223 RewriteImplementationDecl(CategoryImplementation[i]);
3224}
3225
3226void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3227 const std::string &Name,
3228 ValueDecl *VD, bool def) {
3229 assert(BlockByRefDeclNo.count(VD) &&
3230 "RewriteByRefString: ByRef decl missing");
3231 if (def)
3232 ResultStr += "struct ";
3233 ResultStr += "__Block_byref_" + Name +
3234 "_" + utostr(BlockByRefDeclNo[VD]) ;
3235}
3236
3237static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3238 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3239 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3240 return false;
3241}
3242
3243std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3244 StringRef funcName,
3245 std::string Tag) {
3246 const FunctionType *AFT = CE->getFunctionType();
3247 QualType RT = AFT->getResultType();
3248 std::string StructRef = "struct " + Tag;
3249 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3250 funcName.str() + "_" + "block_func_" + utostr(i);
3251
3252 BlockDecl *BD = CE->getBlockDecl();
3253
3254 if (isa<FunctionNoProtoType>(AFT)) {
3255 // No user-supplied arguments. Still need to pass in a pointer to the
3256 // block (to reference imported block decl refs).
3257 S += "(" + StructRef + " *__cself)";
3258 } else if (BD->param_empty()) {
3259 S += "(" + StructRef + " *__cself)";
3260 } else {
3261 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3262 assert(FT && "SynthesizeBlockFunc: No function proto");
3263 S += '(';
3264 // first add the implicit argument.
3265 S += StructRef + " *__cself, ";
3266 std::string ParamStr;
3267 for (BlockDecl::param_iterator AI = BD->param_begin(),
3268 E = BD->param_end(); AI != E; ++AI) {
3269 if (AI != BD->param_begin()) S += ", ";
3270 ParamStr = (*AI)->getNameAsString();
3271 QualType QT = (*AI)->getType();
3272 if (convertBlockPointerToFunctionPointer(QT))
3273 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3274 else
3275 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3276 S += ParamStr;
3277 }
3278 if (FT->isVariadic()) {
3279 if (!BD->param_empty()) S += ", ";
3280 S += "...";
3281 }
3282 S += ')';
3283 }
3284 S += " {\n";
3285
3286 // Create local declarations to avoid rewriting all closure decl ref exprs.
3287 // First, emit a declaration for all "by ref" decls.
3288 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3289 E = BlockByRefDecls.end(); I != E; ++I) {
3290 S += " ";
3291 std::string Name = (*I)->getNameAsString();
3292 std::string TypeString;
3293 RewriteByRefString(TypeString, Name, (*I));
3294 TypeString += " *";
3295 Name = TypeString + Name;
3296 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3297 }
3298 // Next, emit a declaration for all "by copy" declarations.
3299 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3300 E = BlockByCopyDecls.end(); I != E; ++I) {
3301 S += " ";
3302 // Handle nested closure invocation. For example:
3303 //
3304 // void (^myImportedClosure)(void);
3305 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3306 //
3307 // void (^anotherClosure)(void);
3308 // anotherClosure = ^(void) {
3309 // myImportedClosure(); // import and invoke the closure
3310 // };
3311 //
3312 if (isTopLevelBlockPointerType((*I)->getType())) {
3313 RewriteBlockPointerTypeVariable(S, (*I));
3314 S += " = (";
3315 RewriteBlockPointerType(S, (*I)->getType());
3316 S += ")";
3317 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3318 }
3319 else {
3320 std::string Name = (*I)->getNameAsString();
3321 QualType QT = (*I)->getType();
3322 if (HasLocalVariableExternalStorage(*I))
3323 QT = Context->getPointerType(QT);
3324 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3325 S += Name + " = __cself->" +
3326 (*I)->getNameAsString() + "; // bound by copy\n";
3327 }
3328 }
3329 std::string RewrittenStr = RewrittenBlockExprs[CE];
3330 const char *cstr = RewrittenStr.c_str();
3331 while (*cstr++ != '{') ;
3332 S += cstr;
3333 S += "\n";
3334 return S;
3335}
3336
3337std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3338 StringRef funcName,
3339 std::string Tag) {
3340 std::string StructRef = "struct " + Tag;
3341 std::string S = "static void __";
3342
3343 S += funcName;
3344 S += "_block_copy_" + utostr(i);
3345 S += "(" + StructRef;
3346 S += "*dst, " + StructRef;
3347 S += "*src) {";
3348 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3349 E = ImportedBlockDecls.end(); I != E; ++I) {
3350 ValueDecl *VD = (*I);
3351 S += "_Block_object_assign((void*)&dst->";
3352 S += (*I)->getNameAsString();
3353 S += ", (void*)src->";
3354 S += (*I)->getNameAsString();
3355 if (BlockByRefDeclsPtrSet.count((*I)))
3356 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3357 else if (VD->getType()->isBlockPointerType())
3358 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3359 else
3360 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3361 }
3362 S += "}\n";
3363
3364 S += "\nstatic void __";
3365 S += funcName;
3366 S += "_block_dispose_" + utostr(i);
3367 S += "(" + StructRef;
3368 S += "*src) {";
3369 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3370 E = ImportedBlockDecls.end(); I != E; ++I) {
3371 ValueDecl *VD = (*I);
3372 S += "_Block_object_dispose((void*)src->";
3373 S += (*I)->getNameAsString();
3374 if (BlockByRefDeclsPtrSet.count((*I)))
3375 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3376 else if (VD->getType()->isBlockPointerType())
3377 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3378 else
3379 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3380 }
3381 S += "}\n";
3382 return S;
3383}
3384
3385std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3386 std::string Desc) {
3387 std::string S = "\nstruct " + Tag;
3388 std::string Constructor = " " + Tag;
3389
3390 S += " {\n struct __block_impl impl;\n";
3391 S += " struct " + Desc;
3392 S += "* Desc;\n";
3393
3394 Constructor += "(void *fp, "; // Invoke function pointer.
3395 Constructor += "struct " + Desc; // Descriptor pointer.
3396 Constructor += " *desc";
3397
3398 if (BlockDeclRefs.size()) {
3399 // Output all "by copy" declarations.
3400 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3401 E = BlockByCopyDecls.end(); I != E; ++I) {
3402 S += " ";
3403 std::string FieldName = (*I)->getNameAsString();
3404 std::string ArgName = "_" + FieldName;
3405 // Handle nested closure invocation. For example:
3406 //
3407 // void (^myImportedBlock)(void);
3408 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3409 //
3410 // void (^anotherBlock)(void);
3411 // anotherBlock = ^(void) {
3412 // myImportedBlock(); // import and invoke the closure
3413 // };
3414 //
3415 if (isTopLevelBlockPointerType((*I)->getType())) {
3416 S += "struct __block_impl *";
3417 Constructor += ", void *" + ArgName;
3418 } else {
3419 QualType QT = (*I)->getType();
3420 if (HasLocalVariableExternalStorage(*I))
3421 QT = Context->getPointerType(QT);
3422 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3423 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3424 Constructor += ", " + ArgName;
3425 }
3426 S += FieldName + ";\n";
3427 }
3428 // Output all "by ref" declarations.
3429 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3430 E = BlockByRefDecls.end(); I != E; ++I) {
3431 S += " ";
3432 std::string FieldName = (*I)->getNameAsString();
3433 std::string ArgName = "_" + FieldName;
3434 {
3435 std::string TypeString;
3436 RewriteByRefString(TypeString, FieldName, (*I));
3437 TypeString += " *";
3438 FieldName = TypeString + FieldName;
3439 ArgName = TypeString + ArgName;
3440 Constructor += ", " + ArgName;
3441 }
3442 S += FieldName + "; // by ref\n";
3443 }
3444 // Finish writing the constructor.
3445 Constructor += ", int flags=0)";
3446 // Initialize all "by copy" arguments.
3447 bool firsTime = true;
3448 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3449 E = BlockByCopyDecls.end(); I != E; ++I) {
3450 std::string Name = (*I)->getNameAsString();
3451 if (firsTime) {
3452 Constructor += " : ";
3453 firsTime = false;
3454 }
3455 else
3456 Constructor += ", ";
3457 if (isTopLevelBlockPointerType((*I)->getType()))
3458 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3459 else
3460 Constructor += Name + "(_" + Name + ")";
3461 }
3462 // Initialize all "by ref" arguments.
3463 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3464 E = BlockByRefDecls.end(); I != E; ++I) {
3465 std::string Name = (*I)->getNameAsString();
3466 if (firsTime) {
3467 Constructor += " : ";
3468 firsTime = false;
3469 }
3470 else
3471 Constructor += ", ";
3472 Constructor += Name + "(_" + Name + "->__forwarding)";
3473 }
3474
3475 Constructor += " {\n";
3476 if (GlobalVarDecl)
3477 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3478 else
3479 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3480 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3481
3482 Constructor += " Desc = desc;\n";
3483 } else {
3484 // Finish writing the constructor.
3485 Constructor += ", int flags=0) {\n";
3486 if (GlobalVarDecl)
3487 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3488 else
3489 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3490 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3491 Constructor += " Desc = desc;\n";
3492 }
3493 Constructor += " ";
3494 Constructor += "}\n";
3495 S += Constructor;
3496 S += "};\n";
3497 return S;
3498}
3499
3500std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3501 std::string ImplTag, int i,
3502 StringRef FunName,
3503 unsigned hasCopy) {
3504 std::string S = "\nstatic struct " + DescTag;
3505
3506 S += " {\n unsigned long reserved;\n";
3507 S += " unsigned long Block_size;\n";
3508 if (hasCopy) {
3509 S += " void (*copy)(struct ";
3510 S += ImplTag; S += "*, struct ";
3511 S += ImplTag; S += "*);\n";
3512
3513 S += " void (*dispose)(struct ";
3514 S += ImplTag; S += "*);\n";
3515 }
3516 S += "} ";
3517
3518 S += DescTag + "_DATA = { 0, sizeof(struct ";
3519 S += ImplTag + ")";
3520 if (hasCopy) {
3521 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3522 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3523 }
3524 S += "};\n";
3525 return S;
3526}
3527
3528void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3529 StringRef FunName) {
3530 // Insert declaration for the function in which block literal is used.
3531 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3532 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3533 bool RewriteSC = (GlobalVarDecl &&
3534 !Blocks.empty() &&
3535 GlobalVarDecl->getStorageClass() == SC_Static &&
3536 GlobalVarDecl->getType().getCVRQualifiers());
3537 if (RewriteSC) {
3538 std::string SC(" void __");
3539 SC += GlobalVarDecl->getNameAsString();
3540 SC += "() {}";
3541 InsertText(FunLocStart, SC);
3542 }
3543
3544 // Insert closures that were part of the function.
3545 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3546 CollectBlockDeclRefInfo(Blocks[i]);
3547 // Need to copy-in the inner copied-in variables not actually used in this
3548 // block.
3549 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3550 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3551 ValueDecl *VD = Exp->getDecl();
3552 BlockDeclRefs.push_back(Exp);
3553 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3554 BlockByCopyDeclsPtrSet.insert(VD);
3555 BlockByCopyDecls.push_back(VD);
3556 }
3557 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3558 BlockByRefDeclsPtrSet.insert(VD);
3559 BlockByRefDecls.push_back(VD);
3560 }
3561 // imported objects in the inner blocks not used in the outer
3562 // blocks must be copied/disposed in the outer block as well.
3563 if (Exp->isByRef() ||
3564 VD->getType()->isObjCObjectPointerType() ||
3565 VD->getType()->isBlockPointerType())
3566 ImportedBlockDecls.insert(VD);
3567 }
3568
3569 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3570 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3571
3572 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3573
3574 InsertText(FunLocStart, CI);
3575
3576 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3577
3578 InsertText(FunLocStart, CF);
3579
3580 if (ImportedBlockDecls.size()) {
3581 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3582 InsertText(FunLocStart, HF);
3583 }
3584 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3585 ImportedBlockDecls.size() > 0);
3586 InsertText(FunLocStart, BD);
3587
3588 BlockDeclRefs.clear();
3589 BlockByRefDecls.clear();
3590 BlockByRefDeclsPtrSet.clear();
3591 BlockByCopyDecls.clear();
3592 BlockByCopyDeclsPtrSet.clear();
3593 ImportedBlockDecls.clear();
3594 }
3595 if (RewriteSC) {
3596 // Must insert any 'const/volatile/static here. Since it has been
3597 // removed as result of rewriting of block literals.
3598 std::string SC;
3599 if (GlobalVarDecl->getStorageClass() == SC_Static)
3600 SC = "static ";
3601 if (GlobalVarDecl->getType().isConstQualified())
3602 SC += "const ";
3603 if (GlobalVarDecl->getType().isVolatileQualified())
3604 SC += "volatile ";
3605 if (GlobalVarDecl->getType().isRestrictQualified())
3606 SC += "restrict ";
3607 InsertText(FunLocStart, SC);
3608 }
3609
3610 Blocks.clear();
3611 InnerDeclRefsCount.clear();
3612 InnerDeclRefs.clear();
3613 RewrittenBlockExprs.clear();
3614}
3615
3616void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3617 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3618 StringRef FuncName = FD->getName();
3619
3620 SynthesizeBlockLiterals(FunLocStart, FuncName);
3621}
3622
3623static void BuildUniqueMethodName(std::string &Name,
3624 ObjCMethodDecl *MD) {
3625 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3626 Name = IFace->getName();
3627 Name += "__" + MD->getSelector().getAsString();
3628 // Convert colons to underscores.
3629 std::string::size_type loc = 0;
3630 while ((loc = Name.find(":", loc)) != std::string::npos)
3631 Name.replace(loc, 1, "_");
3632}
3633
3634void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3635 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3636 //SourceLocation FunLocStart = MD->getLocStart();
3637 SourceLocation FunLocStart = MD->getLocStart();
3638 std::string FuncName;
3639 BuildUniqueMethodName(FuncName, MD);
3640 SynthesizeBlockLiterals(FunLocStart, FuncName);
3641}
3642
3643void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3644 for (Stmt::child_range CI = S->children(); CI; ++CI)
3645 if (*CI) {
3646 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3647 GetBlockDeclRefExprs(CBE->getBody());
3648 else
3649 GetBlockDeclRefExprs(*CI);
3650 }
3651 // Handle specific things.
3652 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3653 // FIXME: Handle enums.
3654 if (!isa<FunctionDecl>(CDRE->getDecl()))
3655 BlockDeclRefs.push_back(CDRE);
3656 }
3657 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3658 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3659 BlockDeclRefExpr *BDRE =
3660 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3661 DRE->getType(),
3662 VK_LValue, DRE->getLocation(), false);
3663 BlockDeclRefs.push_back(BDRE);
3664 }
3665
3666 return;
3667}
3668
3669void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3670 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
3671 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3672 for (Stmt::child_range CI = S->children(); CI; ++CI)
3673 if (*CI) {
3674 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3675 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3676 GetInnerBlockDeclRefExprs(CBE->getBody(),
3677 InnerBlockDeclRefs,
3678 InnerContexts);
3679 }
3680 else
3681 GetInnerBlockDeclRefExprs(*CI,
3682 InnerBlockDeclRefs,
3683 InnerContexts);
3684
3685 }
3686 // Handle specific things.
3687 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
3688 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
3689 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
3690 InnerBlockDeclRefs.push_back(CDRE);
3691 }
3692 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3693 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3694 if (Var->isFunctionOrMethodVarDecl())
3695 ImportedLocalExternalDecls.insert(Var);
3696 }
3697
3698 return;
3699}
3700
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003701/// convertObjCTypeToCStyleType - This routine converts such objc types
3702/// as qualified objects, and blocks to their closest c/c++ types that
3703/// it can. It returns true if input type was modified.
3704bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3705 QualType oldT = T;
3706 convertBlockPointerToFunctionPointer(T);
3707 if (T->isFunctionPointerType()) {
3708 QualType PointeeTy;
3709 if (const PointerType* PT = T->getAs<PointerType>()) {
3710 PointeeTy = PT->getPointeeType();
3711 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3712 T = convertFunctionTypeOfBlocks(FT);
3713 T = Context->getPointerType(T);
3714 }
3715 }
3716 }
3717
3718 convertToUnqualifiedObjCType(T);
3719 return T != oldT;
3720}
3721
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003722/// convertFunctionTypeOfBlocks - This routine converts a function type
3723/// whose result type may be a block pointer or whose argument type(s)
3724/// might be block pointers to an equivalent function type replacing
3725/// all block pointers to function pointers.
3726QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3727 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3728 // FTP will be null for closures that don't take arguments.
3729 // Generate a funky cast.
3730 SmallVector<QualType, 8> ArgTypes;
3731 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003732 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003733
3734 if (FTP) {
3735 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3736 E = FTP->arg_type_end(); I && (I != E); ++I) {
3737 QualType t = *I;
3738 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003739 if (convertObjCTypeToCStyleType(t))
3740 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003741 ArgTypes.push_back(t);
3742 }
3743 }
3744 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003745 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003746 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3747 else FuncType = QualType(FT, 0);
3748 return FuncType;
3749}
3750
3751Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3752 // Navigate to relevant type information.
3753 const BlockPointerType *CPT = 0;
3754
3755 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3756 CPT = DRE->getType()->getAs<BlockPointerType>();
3757 } else if (const BlockDeclRefExpr *CDRE =
3758 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
3759 CPT = CDRE->getType()->getAs<BlockPointerType>();
3760 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3761 CPT = MExpr->getType()->getAs<BlockPointerType>();
3762 }
3763 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3764 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3765 }
3766 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3767 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3768 else if (const ConditionalOperator *CEXPR =
3769 dyn_cast<ConditionalOperator>(BlockExp)) {
3770 Expr *LHSExp = CEXPR->getLHS();
3771 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3772 Expr *RHSExp = CEXPR->getRHS();
3773 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3774 Expr *CONDExp = CEXPR->getCond();
3775 ConditionalOperator *CondExpr =
3776 new (Context) ConditionalOperator(CONDExp,
3777 SourceLocation(), cast<Expr>(LHSStmt),
3778 SourceLocation(), cast<Expr>(RHSStmt),
3779 Exp->getType(), VK_RValue, OK_Ordinary);
3780 return CondExpr;
3781 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3782 CPT = IRE->getType()->getAs<BlockPointerType>();
3783 } else if (const PseudoObjectExpr *POE
3784 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3785 CPT = POE->getType()->castAs<BlockPointerType>();
3786 } else {
3787 assert(1 && "RewriteBlockClass: Bad type");
3788 }
3789 assert(CPT && "RewriteBlockClass: Bad type");
3790 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3791 assert(FT && "RewriteBlockClass: Bad type");
3792 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3793 // FTP will be null for closures that don't take arguments.
3794
3795 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3796 SourceLocation(), SourceLocation(),
3797 &Context->Idents.get("__block_impl"));
3798 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3799
3800 // Generate a funky cast.
3801 SmallVector<QualType, 8> ArgTypes;
3802
3803 // Push the block argument type.
3804 ArgTypes.push_back(PtrBlock);
3805 if (FTP) {
3806 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3807 E = FTP->arg_type_end(); I && (I != E); ++I) {
3808 QualType t = *I;
3809 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3810 if (!convertBlockPointerToFunctionPointer(t))
3811 convertToUnqualifiedObjCType(t);
3812 ArgTypes.push_back(t);
3813 }
3814 }
3815 // Now do the pointer to function cast.
3816 QualType PtrToFuncCastType
3817 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3818
3819 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3820
3821 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3822 CK_BitCast,
3823 const_cast<Expr*>(BlockExp));
3824 // Don't forget the parens to enforce the proper binding.
3825 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3826 BlkCast);
3827 //PE->dump();
3828
3829 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3830 SourceLocation(),
3831 &Context->Idents.get("FuncPtr"),
3832 Context->VoidPtrTy, 0,
3833 /*BitWidth=*/0, /*Mutable=*/true,
3834 /*HasInit=*/false);
3835 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3836 FD->getType(), VK_LValue,
3837 OK_Ordinary);
3838
3839
3840 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3841 CK_BitCast, ME);
3842 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3843
3844 SmallVector<Expr*, 8> BlkExprs;
3845 // Add the implicit argument.
3846 BlkExprs.push_back(BlkCast);
3847 // Add the user arguments.
3848 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3849 E = Exp->arg_end(); I != E; ++I) {
3850 BlkExprs.push_back(*I);
3851 }
3852 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3853 BlkExprs.size(),
3854 Exp->getType(), VK_RValue,
3855 SourceLocation());
3856 return CE;
3857}
3858
3859// We need to return the rewritten expression to handle cases where the
3860// BlockDeclRefExpr is embedded in another expression being rewritten.
3861// For example:
3862//
3863// int main() {
3864// __block Foo *f;
3865// __block int i;
3866//
3867// void (^myblock)() = ^() {
3868// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3869// i = 77;
3870// };
3871//}
3872Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
3873 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3874 // for each DeclRefExp where BYREFVAR is name of the variable.
3875 ValueDecl *VD;
3876 bool isArrow = true;
3877 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3878 VD = BDRE->getDecl();
3879 else {
3880 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
3881 isArrow = false;
3882 }
3883
3884 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3885 SourceLocation(),
3886 &Context->Idents.get("__forwarding"),
3887 Context->VoidPtrTy, 0,
3888 /*BitWidth=*/0, /*Mutable=*/true,
3889 /*HasInit=*/false);
3890 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3891 FD, SourceLocation(),
3892 FD->getType(), VK_LValue,
3893 OK_Ordinary);
3894
3895 StringRef Name = VD->getName();
3896 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3897 &Context->Idents.get(Name),
3898 Context->VoidPtrTy, 0,
3899 /*BitWidth=*/0, /*Mutable=*/true,
3900 /*HasInit=*/false);
3901 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3902 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3903
3904
3905
3906 // Need parens to enforce precedence.
3907 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3908 DeclRefExp->getExprLoc(),
3909 ME);
3910 ReplaceStmt(DeclRefExp, PE);
3911 return PE;
3912}
3913
3914// Rewrites the imported local variable V with external storage
3915// (static, extern, etc.) as *V
3916//
3917Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3918 ValueDecl *VD = DRE->getDecl();
3919 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3920 if (!ImportedLocalExternalDecls.count(Var))
3921 return DRE;
3922 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3923 VK_LValue, OK_Ordinary,
3924 DRE->getLocation());
3925 // Need parens to enforce precedence.
3926 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3927 Exp);
3928 ReplaceStmt(DRE, PE);
3929 return PE;
3930}
3931
3932void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3933 SourceLocation LocStart = CE->getLParenLoc();
3934 SourceLocation LocEnd = CE->getRParenLoc();
3935
3936 // Need to avoid trying to rewrite synthesized casts.
3937 if (LocStart.isInvalid())
3938 return;
3939 // Need to avoid trying to rewrite casts contained in macros.
3940 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3941 return;
3942
3943 const char *startBuf = SM->getCharacterData(LocStart);
3944 const char *endBuf = SM->getCharacterData(LocEnd);
3945 QualType QT = CE->getType();
3946 const Type* TypePtr = QT->getAs<Type>();
3947 if (isa<TypeOfExprType>(TypePtr)) {
3948 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3949 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3950 std::string TypeAsString = "(";
3951 RewriteBlockPointerType(TypeAsString, QT);
3952 TypeAsString += ")";
3953 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3954 return;
3955 }
3956 // advance the location to startArgList.
3957 const char *argPtr = startBuf;
3958
3959 while (*argPtr++ && (argPtr < endBuf)) {
3960 switch (*argPtr) {
3961 case '^':
3962 // Replace the '^' with '*'.
3963 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3964 ReplaceText(LocStart, 1, "*");
3965 break;
3966 }
3967 }
3968 return;
3969}
3970
3971void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3972 SourceLocation DeclLoc = FD->getLocation();
3973 unsigned parenCount = 0;
3974
3975 // We have 1 or more arguments that have closure pointers.
3976 const char *startBuf = SM->getCharacterData(DeclLoc);
3977 const char *startArgList = strchr(startBuf, '(');
3978
3979 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3980
3981 parenCount++;
3982 // advance the location to startArgList.
3983 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3984 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3985
3986 const char *argPtr = startArgList;
3987
3988 while (*argPtr++ && parenCount) {
3989 switch (*argPtr) {
3990 case '^':
3991 // Replace the '^' with '*'.
3992 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3993 ReplaceText(DeclLoc, 1, "*");
3994 break;
3995 case '(':
3996 parenCount++;
3997 break;
3998 case ')':
3999 parenCount--;
4000 break;
4001 }
4002 }
4003 return;
4004}
4005
4006bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4007 const FunctionProtoType *FTP;
4008 const PointerType *PT = QT->getAs<PointerType>();
4009 if (PT) {
4010 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4011 } else {
4012 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4013 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4014 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4015 }
4016 if (FTP) {
4017 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4018 E = FTP->arg_type_end(); I != E; ++I)
4019 if (isTopLevelBlockPointerType(*I))
4020 return true;
4021 }
4022 return false;
4023}
4024
4025bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4026 const FunctionProtoType *FTP;
4027 const PointerType *PT = QT->getAs<PointerType>();
4028 if (PT) {
4029 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4030 } else {
4031 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4032 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4033 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4034 }
4035 if (FTP) {
4036 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4037 E = FTP->arg_type_end(); I != E; ++I) {
4038 if ((*I)->isObjCQualifiedIdType())
4039 return true;
4040 if ((*I)->isObjCObjectPointerType() &&
4041 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4042 return true;
4043 }
4044
4045 }
4046 return false;
4047}
4048
4049void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4050 const char *&RParen) {
4051 const char *argPtr = strchr(Name, '(');
4052 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4053
4054 LParen = argPtr; // output the start.
4055 argPtr++; // skip past the left paren.
4056 unsigned parenCount = 1;
4057
4058 while (*argPtr && parenCount) {
4059 switch (*argPtr) {
4060 case '(': parenCount++; break;
4061 case ')': parenCount--; break;
4062 default: break;
4063 }
4064 if (parenCount) argPtr++;
4065 }
4066 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4067 RParen = argPtr; // output the end
4068}
4069
4070void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4071 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4072 RewriteBlockPointerFunctionArgs(FD);
4073 return;
4074 }
4075 // Handle Variables and Typedefs.
4076 SourceLocation DeclLoc = ND->getLocation();
4077 QualType DeclT;
4078 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4079 DeclT = VD->getType();
4080 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4081 DeclT = TDD->getUnderlyingType();
4082 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4083 DeclT = FD->getType();
4084 else
4085 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4086
4087 const char *startBuf = SM->getCharacterData(DeclLoc);
4088 const char *endBuf = startBuf;
4089 // scan backward (from the decl location) for the end of the previous decl.
4090 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4091 startBuf--;
4092 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4093 std::string buf;
4094 unsigned OrigLength=0;
4095 // *startBuf != '^' if we are dealing with a pointer to function that
4096 // may take block argument types (which will be handled below).
4097 if (*startBuf == '^') {
4098 // Replace the '^' with '*', computing a negative offset.
4099 buf = '*';
4100 startBuf++;
4101 OrigLength++;
4102 }
4103 while (*startBuf != ')') {
4104 buf += *startBuf;
4105 startBuf++;
4106 OrigLength++;
4107 }
4108 buf += ')';
4109 OrigLength++;
4110
4111 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4112 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4113 // Replace the '^' with '*' for arguments.
4114 // Replace id<P> with id/*<>*/
4115 DeclLoc = ND->getLocation();
4116 startBuf = SM->getCharacterData(DeclLoc);
4117 const char *argListBegin, *argListEnd;
4118 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4119 while (argListBegin < argListEnd) {
4120 if (*argListBegin == '^')
4121 buf += '*';
4122 else if (*argListBegin == '<') {
4123 buf += "/*";
4124 buf += *argListBegin++;
4125 OrigLength++;;
4126 while (*argListBegin != '>') {
4127 buf += *argListBegin++;
4128 OrigLength++;
4129 }
4130 buf += *argListBegin;
4131 buf += "*/";
4132 }
4133 else
4134 buf += *argListBegin;
4135 argListBegin++;
4136 OrigLength++;
4137 }
4138 buf += ')';
4139 OrigLength++;
4140 }
4141 ReplaceText(Start, OrigLength, buf);
4142
4143 return;
4144}
4145
4146
4147/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4148/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4149/// struct Block_byref_id_object *src) {
4150/// _Block_object_assign (&_dest->object, _src->object,
4151/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4152/// [|BLOCK_FIELD_IS_WEAK]) // object
4153/// _Block_object_assign(&_dest->object, _src->object,
4154/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4155/// [|BLOCK_FIELD_IS_WEAK]) // block
4156/// }
4157/// And:
4158/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4159/// _Block_object_dispose(_src->object,
4160/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4161/// [|BLOCK_FIELD_IS_WEAK]) // object
4162/// _Block_object_dispose(_src->object,
4163/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4164/// [|BLOCK_FIELD_IS_WEAK]) // block
4165/// }
4166
4167std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4168 int flag) {
4169 std::string S;
4170 if (CopyDestroyCache.count(flag))
4171 return S;
4172 CopyDestroyCache.insert(flag);
4173 S = "static void __Block_byref_id_object_copy_";
4174 S += utostr(flag);
4175 S += "(void *dst, void *src) {\n";
4176
4177 // offset into the object pointer is computed as:
4178 // void * + void* + int + int + void* + void *
4179 unsigned IntSize =
4180 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4181 unsigned VoidPtrSize =
4182 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4183
4184 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4185 S += " _Block_object_assign((char*)dst + ";
4186 S += utostr(offset);
4187 S += ", *(void * *) ((char*)src + ";
4188 S += utostr(offset);
4189 S += "), ";
4190 S += utostr(flag);
4191 S += ");\n}\n";
4192
4193 S += "static void __Block_byref_id_object_dispose_";
4194 S += utostr(flag);
4195 S += "(void *src) {\n";
4196 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4197 S += utostr(offset);
4198 S += "), ";
4199 S += utostr(flag);
4200 S += ");\n}\n";
4201 return S;
4202}
4203
4204/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4205/// the declaration into:
4206/// struct __Block_byref_ND {
4207/// void *__isa; // NULL for everything except __weak pointers
4208/// struct __Block_byref_ND *__forwarding;
4209/// int32_t __flags;
4210/// int32_t __size;
4211/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4212/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4213/// typex ND;
4214/// };
4215///
4216/// It then replaces declaration of ND variable with:
4217/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4218/// __size=sizeof(struct __Block_byref_ND),
4219/// ND=initializer-if-any};
4220///
4221///
4222void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4223 // Insert declaration for the function in which block literal is
4224 // used.
4225 if (CurFunctionDeclToDeclareForBlock)
4226 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4227 int flag = 0;
4228 int isa = 0;
4229 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4230 if (DeclLoc.isInvalid())
4231 // If type location is missing, it is because of missing type (a warning).
4232 // Use variable's location which is good for this case.
4233 DeclLoc = ND->getLocation();
4234 const char *startBuf = SM->getCharacterData(DeclLoc);
4235 SourceLocation X = ND->getLocEnd();
4236 X = SM->getExpansionLoc(X);
4237 const char *endBuf = SM->getCharacterData(X);
4238 std::string Name(ND->getNameAsString());
4239 std::string ByrefType;
4240 RewriteByRefString(ByrefType, Name, ND, true);
4241 ByrefType += " {\n";
4242 ByrefType += " void *__isa;\n";
4243 RewriteByRefString(ByrefType, Name, ND);
4244 ByrefType += " *__forwarding;\n";
4245 ByrefType += " int __flags;\n";
4246 ByrefType += " int __size;\n";
4247 // Add void *__Block_byref_id_object_copy;
4248 // void *__Block_byref_id_object_dispose; if needed.
4249 QualType Ty = ND->getType();
4250 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4251 if (HasCopyAndDispose) {
4252 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4253 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4254 }
4255
4256 QualType T = Ty;
4257 (void)convertBlockPointerToFunctionPointer(T);
4258 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4259
4260 ByrefType += " " + Name + ";\n";
4261 ByrefType += "};\n";
4262 // Insert this type in global scope. It is needed by helper function.
4263 SourceLocation FunLocStart;
4264 if (CurFunctionDef)
4265 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4266 else {
4267 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4268 FunLocStart = CurMethodDef->getLocStart();
4269 }
4270 InsertText(FunLocStart, ByrefType);
4271 if (Ty.isObjCGCWeak()) {
4272 flag |= BLOCK_FIELD_IS_WEAK;
4273 isa = 1;
4274 }
4275
4276 if (HasCopyAndDispose) {
4277 flag = BLOCK_BYREF_CALLER;
4278 QualType Ty = ND->getType();
4279 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4280 if (Ty->isBlockPointerType())
4281 flag |= BLOCK_FIELD_IS_BLOCK;
4282 else
4283 flag |= BLOCK_FIELD_IS_OBJECT;
4284 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4285 if (!HF.empty())
4286 InsertText(FunLocStart, HF);
4287 }
4288
4289 // struct __Block_byref_ND ND =
4290 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4291 // initializer-if-any};
4292 bool hasInit = (ND->getInit() != 0);
4293 unsigned flags = 0;
4294 if (HasCopyAndDispose)
4295 flags |= BLOCK_HAS_COPY_DISPOSE;
4296 Name = ND->getNameAsString();
4297 ByrefType.clear();
4298 RewriteByRefString(ByrefType, Name, ND);
4299 std::string ForwardingCastType("(");
4300 ForwardingCastType += ByrefType + " *)";
4301 if (!hasInit) {
4302 ByrefType += " " + Name + " = {(void*)";
4303 ByrefType += utostr(isa);
4304 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4305 ByrefType += utostr(flags);
4306 ByrefType += ", ";
4307 ByrefType += "sizeof(";
4308 RewriteByRefString(ByrefType, Name, ND);
4309 ByrefType += ")";
4310 if (HasCopyAndDispose) {
4311 ByrefType += ", __Block_byref_id_object_copy_";
4312 ByrefType += utostr(flag);
4313 ByrefType += ", __Block_byref_id_object_dispose_";
4314 ByrefType += utostr(flag);
4315 }
4316 ByrefType += "};\n";
4317 unsigned nameSize = Name.size();
4318 // for block or function pointer declaration. Name is aleady
4319 // part of the declaration.
4320 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4321 nameSize = 1;
4322 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4323 }
4324 else {
4325 SourceLocation startLoc;
4326 Expr *E = ND->getInit();
4327 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4328 startLoc = ECE->getLParenLoc();
4329 else
4330 startLoc = E->getLocStart();
4331 startLoc = SM->getExpansionLoc(startLoc);
4332 endBuf = SM->getCharacterData(startLoc);
4333 ByrefType += " " + Name;
4334 ByrefType += " = {(void*)";
4335 ByrefType += utostr(isa);
4336 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4337 ByrefType += utostr(flags);
4338 ByrefType += ", ";
4339 ByrefType += "sizeof(";
4340 RewriteByRefString(ByrefType, Name, ND);
4341 ByrefType += "), ";
4342 if (HasCopyAndDispose) {
4343 ByrefType += "__Block_byref_id_object_copy_";
4344 ByrefType += utostr(flag);
4345 ByrefType += ", __Block_byref_id_object_dispose_";
4346 ByrefType += utostr(flag);
4347 ByrefType += ", ";
4348 }
4349 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4350
4351 // Complete the newly synthesized compound expression by inserting a right
4352 // curly brace before the end of the declaration.
4353 // FIXME: This approach avoids rewriting the initializer expression. It
4354 // also assumes there is only one declarator. For example, the following
4355 // isn't currently supported by this routine (in general):
4356 //
4357 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4358 //
4359 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4360 const char *semiBuf = strchr(startInitializerBuf, ';');
4361 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4362 SourceLocation semiLoc =
4363 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4364
4365 InsertText(semiLoc, "}");
4366 }
4367 return;
4368}
4369
4370void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4371 // Add initializers for any closure decl refs.
4372 GetBlockDeclRefExprs(Exp->getBody());
4373 if (BlockDeclRefs.size()) {
4374 // Unique all "by copy" declarations.
4375 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4376 if (!BlockDeclRefs[i]->isByRef()) {
4377 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4378 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4379 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4380 }
4381 }
4382 // Unique all "by ref" declarations.
4383 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4384 if (BlockDeclRefs[i]->isByRef()) {
4385 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4386 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4387 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4388 }
4389 }
4390 // Find any imported blocks...they will need special attention.
4391 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4392 if (BlockDeclRefs[i]->isByRef() ||
4393 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4394 BlockDeclRefs[i]->getType()->isBlockPointerType())
4395 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4396 }
4397}
4398
4399FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4400 IdentifierInfo *ID = &Context->Idents.get(name);
4401 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4402 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4403 SourceLocation(), ID, FType, 0, SC_Extern,
4404 SC_None, false, false);
4405}
4406
4407Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
4408 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
4409 const BlockDecl *block = Exp->getBlockDecl();
4410 Blocks.push_back(Exp);
4411
4412 CollectBlockDeclRefInfo(Exp);
4413
4414 // Add inner imported variables now used in current block.
4415 int countOfInnerDecls = 0;
4416 if (!InnerBlockDeclRefs.empty()) {
4417 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4418 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4419 ValueDecl *VD = Exp->getDecl();
4420 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4421 // We need to save the copied-in variables in nested
4422 // blocks because it is needed at the end for some of the API generations.
4423 // See SynthesizeBlockLiterals routine.
4424 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4425 BlockDeclRefs.push_back(Exp);
4426 BlockByCopyDeclsPtrSet.insert(VD);
4427 BlockByCopyDecls.push_back(VD);
4428 }
4429 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4430 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4431 BlockDeclRefs.push_back(Exp);
4432 BlockByRefDeclsPtrSet.insert(VD);
4433 BlockByRefDecls.push_back(VD);
4434 }
4435 }
4436 // Find any imported blocks...they will need special attention.
4437 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4438 if (InnerBlockDeclRefs[i]->isByRef() ||
4439 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4440 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4441 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4442 }
4443 InnerDeclRefsCount.push_back(countOfInnerDecls);
4444
4445 std::string FuncName;
4446
4447 if (CurFunctionDef)
4448 FuncName = CurFunctionDef->getNameAsString();
4449 else if (CurMethodDef)
4450 BuildUniqueMethodName(FuncName, CurMethodDef);
4451 else if (GlobalVarDecl)
4452 FuncName = std::string(GlobalVarDecl->getNameAsString());
4453
4454 std::string BlockNumber = utostr(Blocks.size()-1);
4455
4456 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4457 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4458
4459 // Get a pointer to the function type so we can cast appropriately.
4460 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4461 QualType FType = Context->getPointerType(BFT);
4462
4463 FunctionDecl *FD;
4464 Expr *NewRep;
4465
4466 // Simulate a contructor call...
4467 FD = SynthBlockInitFunctionDecl(Tag);
4468 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4469 SourceLocation());
4470
4471 SmallVector<Expr*, 4> InitExprs;
4472
4473 // Initialize the block function.
4474 FD = SynthBlockInitFunctionDecl(Func);
4475 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4476 SourceLocation());
4477 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4478 CK_BitCast, Arg);
4479 InitExprs.push_back(castExpr);
4480
4481 // Initialize the block descriptor.
4482 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4483
4484 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4485 SourceLocation(), SourceLocation(),
4486 &Context->Idents.get(DescData.c_str()),
4487 Context->VoidPtrTy, 0,
4488 SC_Static, SC_None);
4489 UnaryOperator *DescRefExpr =
4490 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4491 Context->VoidPtrTy,
4492 VK_LValue,
4493 SourceLocation()),
4494 UO_AddrOf,
4495 Context->getPointerType(Context->VoidPtrTy),
4496 VK_RValue, OK_Ordinary,
4497 SourceLocation());
4498 InitExprs.push_back(DescRefExpr);
4499
4500 // Add initializers for any closure decl refs.
4501 if (BlockDeclRefs.size()) {
4502 Expr *Exp;
4503 // Output all "by copy" declarations.
4504 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4505 E = BlockByCopyDecls.end(); I != E; ++I) {
4506 if (isObjCType((*I)->getType())) {
4507 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4508 FD = SynthBlockInitFunctionDecl((*I)->getName());
4509 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4510 SourceLocation());
4511 if (HasLocalVariableExternalStorage(*I)) {
4512 QualType QT = (*I)->getType();
4513 QT = Context->getPointerType(QT);
4514 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4515 OK_Ordinary, SourceLocation());
4516 }
4517 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4518 FD = SynthBlockInitFunctionDecl((*I)->getName());
4519 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4520 SourceLocation());
4521 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4522 CK_BitCast, Arg);
4523 } else {
4524 FD = SynthBlockInitFunctionDecl((*I)->getName());
4525 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4526 SourceLocation());
4527 if (HasLocalVariableExternalStorage(*I)) {
4528 QualType QT = (*I)->getType();
4529 QT = Context->getPointerType(QT);
4530 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4531 OK_Ordinary, SourceLocation());
4532 }
4533
4534 }
4535 InitExprs.push_back(Exp);
4536 }
4537 // Output all "by ref" declarations.
4538 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4539 E = BlockByRefDecls.end(); I != E; ++I) {
4540 ValueDecl *ND = (*I);
4541 std::string Name(ND->getNameAsString());
4542 std::string RecName;
4543 RewriteByRefString(RecName, Name, ND, true);
4544 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4545 + sizeof("struct"));
4546 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4547 SourceLocation(), SourceLocation(),
4548 II);
4549 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4550 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4551
4552 FD = SynthBlockInitFunctionDecl((*I)->getName());
4553 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4554 SourceLocation());
4555 bool isNestedCapturedVar = false;
4556 if (block)
4557 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4558 ce = block->capture_end(); ci != ce; ++ci) {
4559 const VarDecl *variable = ci->getVariable();
4560 if (variable == ND && ci->isNested()) {
4561 assert (ci->isByRef() &&
4562 "SynthBlockInitExpr - captured block variable is not byref");
4563 isNestedCapturedVar = true;
4564 break;
4565 }
4566 }
4567 // captured nested byref variable has its address passed. Do not take
4568 // its address again.
4569 if (!isNestedCapturedVar)
4570 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4571 Context->getPointerType(Exp->getType()),
4572 VK_RValue, OK_Ordinary, SourceLocation());
4573 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4574 InitExprs.push_back(Exp);
4575 }
4576 }
4577 if (ImportedBlockDecls.size()) {
4578 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4579 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4580 unsigned IntSize =
4581 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4582 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4583 Context->IntTy, SourceLocation());
4584 InitExprs.push_back(FlagExp);
4585 }
4586 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4587 FType, VK_LValue, SourceLocation());
4588 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4589 Context->getPointerType(NewRep->getType()),
4590 VK_RValue, OK_Ordinary, SourceLocation());
4591 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4592 NewRep);
4593 BlockDeclRefs.clear();
4594 BlockByRefDecls.clear();
4595 BlockByRefDeclsPtrSet.clear();
4596 BlockByCopyDecls.clear();
4597 BlockByCopyDeclsPtrSet.clear();
4598 ImportedBlockDecls.clear();
4599 return NewRep;
4600}
4601
4602bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4603 if (const ObjCForCollectionStmt * CS =
4604 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4605 return CS->getElement() == DS;
4606 return false;
4607}
4608
4609//===----------------------------------------------------------------------===//
4610// Function Body / Expression rewriting
4611//===----------------------------------------------------------------------===//
4612
4613Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4614 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4615 isa<DoStmt>(S) || isa<ForStmt>(S))
4616 Stmts.push_back(S);
4617 else if (isa<ObjCForCollectionStmt>(S)) {
4618 Stmts.push_back(S);
4619 ObjCBcLabelNo.push_back(++BcLabelCount);
4620 }
4621
4622 // Pseudo-object operations and ivar references need special
4623 // treatment because we're going to recursively rewrite them.
4624 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4625 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4626 return RewritePropertyOrImplicitSetter(PseudoOp);
4627 } else {
4628 return RewritePropertyOrImplicitGetter(PseudoOp);
4629 }
4630 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4631 return RewriteObjCIvarRefExpr(IvarRefExpr);
4632 }
4633
4634 SourceRange OrigStmtRange = S->getSourceRange();
4635
4636 // Perform a bottom up rewrite of all children.
4637 for (Stmt::child_range CI = S->children(); CI; ++CI)
4638 if (*CI) {
4639 Stmt *childStmt = (*CI);
4640 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4641 if (newStmt) {
4642 *CI = newStmt;
4643 }
4644 }
4645
4646 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4647 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
4648 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4649 InnerContexts.insert(BE->getBlockDecl());
4650 ImportedLocalExternalDecls.clear();
4651 GetInnerBlockDeclRefExprs(BE->getBody(),
4652 InnerBlockDeclRefs, InnerContexts);
4653 // Rewrite the block body in place.
4654 Stmt *SaveCurrentBody = CurrentBody;
4655 CurrentBody = BE->getBody();
4656 PropParentMap = 0;
4657 // block literal on rhs of a property-dot-sytax assignment
4658 // must be replaced by its synthesize ast so getRewrittenText
4659 // works as expected. In this case, what actually ends up on RHS
4660 // is the blockTranscribed which is the helper function for the
4661 // block literal; as in: self.c = ^() {[ace ARR];};
4662 bool saveDisableReplaceStmt = DisableReplaceStmt;
4663 DisableReplaceStmt = false;
4664 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4665 DisableReplaceStmt = saveDisableReplaceStmt;
4666 CurrentBody = SaveCurrentBody;
4667 PropParentMap = 0;
4668 ImportedLocalExternalDecls.clear();
4669 // Now we snarf the rewritten text and stash it away for later use.
4670 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4671 RewrittenBlockExprs[BE] = Str;
4672
4673 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4674
4675 //blockTranscribed->dump();
4676 ReplaceStmt(S, blockTranscribed);
4677 return blockTranscribed;
4678 }
4679 // Handle specific things.
4680 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4681 return RewriteAtEncode(AtEncode);
4682
4683 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4684 return RewriteAtSelector(AtSelector);
4685
4686 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4687 return RewriteObjCStringLiteral(AtString);
4688
4689 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4690#if 0
4691 // Before we rewrite it, put the original message expression in a comment.
4692 SourceLocation startLoc = MessExpr->getLocStart();
4693 SourceLocation endLoc = MessExpr->getLocEnd();
4694
4695 const char *startBuf = SM->getCharacterData(startLoc);
4696 const char *endBuf = SM->getCharacterData(endLoc);
4697
4698 std::string messString;
4699 messString += "// ";
4700 messString.append(startBuf, endBuf-startBuf+1);
4701 messString += "\n";
4702
4703 // FIXME: Missing definition of
4704 // InsertText(clang::SourceLocation, char const*, unsigned int).
4705 // InsertText(startLoc, messString.c_str(), messString.size());
4706 // Tried this, but it didn't work either...
4707 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4708#endif
4709 return RewriteMessageExpr(MessExpr);
4710 }
4711
4712 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4713 return RewriteObjCTryStmt(StmtTry);
4714
4715 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4716 return RewriteObjCSynchronizedStmt(StmtTry);
4717
4718 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4719 return RewriteObjCThrowStmt(StmtThrow);
4720
4721 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4722 return RewriteObjCProtocolExpr(ProtocolExp);
4723
4724 if (ObjCForCollectionStmt *StmtForCollection =
4725 dyn_cast<ObjCForCollectionStmt>(S))
4726 return RewriteObjCForCollectionStmt(StmtForCollection,
4727 OrigStmtRange.getEnd());
4728 if (BreakStmt *StmtBreakStmt =
4729 dyn_cast<BreakStmt>(S))
4730 return RewriteBreakStmt(StmtBreakStmt);
4731 if (ContinueStmt *StmtContinueStmt =
4732 dyn_cast<ContinueStmt>(S))
4733 return RewriteContinueStmt(StmtContinueStmt);
4734
4735 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4736 // and cast exprs.
4737 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4738 // FIXME: What we're doing here is modifying the type-specifier that
4739 // precedes the first Decl. In the future the DeclGroup should have
4740 // a separate type-specifier that we can rewrite.
4741 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4742 // the context of an ObjCForCollectionStmt. For example:
4743 // NSArray *someArray;
4744 // for (id <FooProtocol> index in someArray) ;
4745 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4746 // and it depends on the original text locations/positions.
4747 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4748 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4749
4750 // Blocks rewrite rules.
4751 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4752 DI != DE; ++DI) {
4753 Decl *SD = *DI;
4754 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4755 if (isTopLevelBlockPointerType(ND->getType()))
4756 RewriteBlockPointerDecl(ND);
4757 else if (ND->getType()->isFunctionPointerType())
4758 CheckFunctionPointerDecl(ND->getType(), ND);
4759 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4760 if (VD->hasAttr<BlocksAttr>()) {
4761 static unsigned uniqueByrefDeclCount = 0;
4762 assert(!BlockByRefDeclNo.count(ND) &&
4763 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4764 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4765 RewriteByRefVar(VD);
4766 }
4767 else
4768 RewriteTypeOfDecl(VD);
4769 }
4770 }
4771 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4772 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4773 RewriteBlockPointerDecl(TD);
4774 else if (TD->getUnderlyingType()->isFunctionPointerType())
4775 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4776 }
4777 }
4778 }
4779
4780 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4781 RewriteObjCQualifiedInterfaceTypes(CE);
4782
4783 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4784 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4785 assert(!Stmts.empty() && "Statement stack is empty");
4786 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4787 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4788 && "Statement stack mismatch");
4789 Stmts.pop_back();
4790 }
4791 // Handle blocks rewriting.
4792 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4793 if (BDRE->isByRef())
4794 return RewriteBlockDeclRefExpr(BDRE);
4795 }
4796 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4797 ValueDecl *VD = DRE->getDecl();
4798 if (VD->hasAttr<BlocksAttr>())
4799 return RewriteBlockDeclRefExpr(DRE);
4800 if (HasLocalVariableExternalStorage(VD))
4801 return RewriteLocalVariableExternalStorage(DRE);
4802 }
4803
4804 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4805 if (CE->getCallee()->getType()->isBlockPointerType()) {
4806 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4807 ReplaceStmt(S, BlockCall);
4808 return BlockCall;
4809 }
4810 }
4811 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4812 RewriteCastExpr(CE);
4813 }
4814#if 0
4815 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4816 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4817 ICE->getSubExpr(),
4818 SourceLocation());
4819 // Get the new text.
4820 std::string SStr;
4821 llvm::raw_string_ostream Buf(SStr);
4822 Replacement->printPretty(Buf, *Context);
4823 const std::string &Str = Buf.str();
4824
4825 printf("CAST = %s\n", &Str[0]);
4826 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4827 delete S;
4828 return Replacement;
4829 }
4830#endif
4831 // Return this stmt unmodified.
4832 return S;
4833}
4834
4835void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4836 for (RecordDecl::field_iterator i = RD->field_begin(),
4837 e = RD->field_end(); i != e; ++i) {
4838 FieldDecl *FD = *i;
4839 if (isTopLevelBlockPointerType(FD->getType()))
4840 RewriteBlockPointerDecl(FD);
4841 if (FD->getType()->isObjCQualifiedIdType() ||
4842 FD->getType()->isObjCQualifiedInterfaceType())
4843 RewriteObjCQualifiedInterfaceTypes(FD);
4844 }
4845}
4846
4847/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4848/// main file of the input.
4849void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4850 switch (D->getKind()) {
4851 case Decl::Function: {
4852 FunctionDecl *FD = cast<FunctionDecl>(D);
4853 if (FD->isOverloadedOperator())
4854 return;
4855
4856 // Since function prototypes don't have ParmDecl's, we check the function
4857 // prototype. This enables us to rewrite function declarations and
4858 // definitions using the same code.
4859 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4860
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004861 if (!FD->isThisDeclarationADefinition())
4862 break;
4863
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004864 // FIXME: If this should support Obj-C++, support CXXTryStmt
4865 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4866 CurFunctionDef = FD;
4867 CurFunctionDeclToDeclareForBlock = FD;
4868 CurrentBody = Body;
4869 Body =
4870 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4871 FD->setBody(Body);
4872 CurrentBody = 0;
4873 if (PropParentMap) {
4874 delete PropParentMap;
4875 PropParentMap = 0;
4876 }
4877 // This synthesizes and inserts the block "impl" struct, invoke function,
4878 // and any copy/dispose helper functions.
4879 InsertBlockLiteralsWithinFunction(FD);
4880 CurFunctionDef = 0;
4881 CurFunctionDeclToDeclareForBlock = 0;
4882 }
4883 break;
4884 }
4885 case Decl::ObjCMethod: {
4886 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4887 if (CompoundStmt *Body = MD->getCompoundBody()) {
4888 CurMethodDef = MD;
4889 CurrentBody = Body;
4890 Body =
4891 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4892 MD->setBody(Body);
4893 CurrentBody = 0;
4894 if (PropParentMap) {
4895 delete PropParentMap;
4896 PropParentMap = 0;
4897 }
4898 InsertBlockLiteralsWithinMethod(MD);
4899 CurMethodDef = 0;
4900 }
4901 break;
4902 }
4903 case Decl::ObjCImplementation: {
4904 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4905 ClassImplementation.push_back(CI);
4906 break;
4907 }
4908 case Decl::ObjCCategoryImpl: {
4909 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4910 CategoryImplementation.push_back(CI);
4911 break;
4912 }
4913 case Decl::Var: {
4914 VarDecl *VD = cast<VarDecl>(D);
4915 RewriteObjCQualifiedInterfaceTypes(VD);
4916 if (isTopLevelBlockPointerType(VD->getType()))
4917 RewriteBlockPointerDecl(VD);
4918 else if (VD->getType()->isFunctionPointerType()) {
4919 CheckFunctionPointerDecl(VD->getType(), VD);
4920 if (VD->getInit()) {
4921 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4922 RewriteCastExpr(CE);
4923 }
4924 }
4925 } else if (VD->getType()->isRecordType()) {
4926 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4927 if (RD->isCompleteDefinition())
4928 RewriteRecordBody(RD);
4929 }
4930 if (VD->getInit()) {
4931 GlobalVarDecl = VD;
4932 CurrentBody = VD->getInit();
4933 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4934 CurrentBody = 0;
4935 if (PropParentMap) {
4936 delete PropParentMap;
4937 PropParentMap = 0;
4938 }
4939 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4940 GlobalVarDecl = 0;
4941
4942 // This is needed for blocks.
4943 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4944 RewriteCastExpr(CE);
4945 }
4946 }
4947 break;
4948 }
4949 case Decl::TypeAlias:
4950 case Decl::Typedef: {
4951 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4952 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4953 RewriteBlockPointerDecl(TD);
4954 else if (TD->getUnderlyingType()->isFunctionPointerType())
4955 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4956 }
4957 break;
4958 }
4959 case Decl::CXXRecord:
4960 case Decl::Record: {
4961 RecordDecl *RD = cast<RecordDecl>(D);
4962 if (RD->isCompleteDefinition())
4963 RewriteRecordBody(RD);
4964 break;
4965 }
4966 default:
4967 break;
4968 }
4969 // Nothing yet.
4970}
4971
4972void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
4973 if (Diags.hasErrorOccurred())
4974 return;
4975
4976 RewriteInclude();
4977
4978 // Here's a great place to add any extra declarations that may be needed.
4979 // Write out meta data for each @protocol(<expr>).
4980 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
4981 E = ProtocolExprDecls.end(); I != E; ++I)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00004982 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004983
4984 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
4985 if (ClassImplementation.size() || CategoryImplementation.size())
4986 RewriteImplementations();
4987
4988 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4989 // we are done.
4990 if (const RewriteBuffer *RewriteBuf =
4991 Rewrite.getRewriteBufferFor(MainFileID)) {
4992 //printf("Changed:\n");
4993 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4994 } else {
4995 llvm::errs() << "No changes\n";
4996 }
4997
4998 if (ClassImplementation.size() || CategoryImplementation.size() ||
4999 ProtocolExprDecls.size()) {
5000 // Rewrite Objective-c meta data*
5001 std::string ResultStr;
5002 RewriteMetaDataIntoBuffer(ResultStr);
5003 // Emit metadata.
5004 *OutFile << ResultStr;
5005 }
5006 OutFile->flush();
5007}
5008
5009void RewriteModernObjC::Initialize(ASTContext &context) {
5010 InitializeCommon(context);
5011
5012 // declaring objc_selector outside the parameter list removes a silly
5013 // scope related warning...
5014 if (IsHeader)
5015 Preamble = "#pragma once\n";
5016 Preamble += "struct objc_selector; struct objc_class;\n";
5017 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5018 Preamble += "struct objc_object *superClass; ";
5019 if (LangOpts.MicrosoftExt) {
5020 // Add a constructor for creating temporary objects.
5021 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5022 ": ";
5023 Preamble += "object(o), superClass(s) {} ";
5024 }
5025 Preamble += "};\n";
5026 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5027 Preamble += "typedef struct objc_object Protocol;\n";
5028 Preamble += "#define _REWRITER_typedef_Protocol\n";
5029 Preamble += "#endif\n";
5030 if (LangOpts.MicrosoftExt) {
5031 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5032 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5033 } else
5034 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5035 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5036 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5037 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5038 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5039 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5040 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5041 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5042 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5043 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5044 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5045 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5046 Preamble += "(const char *);\n";
5047 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5048 Preamble += "(struct objc_class *);\n";
5049 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5050 Preamble += "(const char *);\n";
5051 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5052 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5053 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5054 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5055 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5056 Preamble += "(struct objc_class *, struct objc_object *);\n";
5057 // @synchronized hooks.
5058 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5059 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5060 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5061 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5062 Preamble += "struct __objcFastEnumerationState {\n\t";
5063 Preamble += "unsigned long state;\n\t";
5064 Preamble += "void **itemsPtr;\n\t";
5065 Preamble += "unsigned long *mutationsPtr;\n\t";
5066 Preamble += "unsigned long extra[5];\n};\n";
5067 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5068 Preamble += "#define __FASTENUMERATIONSTATE\n";
5069 Preamble += "#endif\n";
5070 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5071 Preamble += "struct __NSConstantStringImpl {\n";
5072 Preamble += " int *isa;\n";
5073 Preamble += " int flags;\n";
5074 Preamble += " char *str;\n";
5075 Preamble += " long length;\n";
5076 Preamble += "};\n";
5077 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5078 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5079 Preamble += "#else\n";
5080 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5081 Preamble += "#endif\n";
5082 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5083 Preamble += "#endif\n";
5084 // Blocks preamble.
5085 Preamble += "#ifndef BLOCK_IMPL\n";
5086 Preamble += "#define BLOCK_IMPL\n";
5087 Preamble += "struct __block_impl {\n";
5088 Preamble += " void *isa;\n";
5089 Preamble += " int Flags;\n";
5090 Preamble += " int Reserved;\n";
5091 Preamble += " void *FuncPtr;\n";
5092 Preamble += "};\n";
5093 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5094 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5095 Preamble += "extern \"C\" __declspec(dllexport) "
5096 "void _Block_object_assign(void *, const void *, const int);\n";
5097 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5098 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5099 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5100 Preamble += "#else\n";
5101 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5102 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5103 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5104 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5105 Preamble += "#endif\n";
5106 Preamble += "#endif\n";
5107 if (LangOpts.MicrosoftExt) {
5108 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5109 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5110 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5111 Preamble += "#define __attribute__(X)\n";
5112 Preamble += "#endif\n";
5113 Preamble += "#define __weak\n";
5114 }
5115 else {
5116 Preamble += "#define __block\n";
5117 Preamble += "#define __weak\n";
5118 }
5119 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5120 // as this avoids warning in any 64bit/32bit compilation model.
5121 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5122}
5123
5124/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5125/// ivar offset.
5126void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5127 std::string &Result) {
5128 if (ivar->isBitField()) {
5129 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5130 // place all bitfields at offset 0.
5131 Result += "0";
5132 } else {
5133 Result += "__OFFSETOFIVAR__(struct ";
5134 Result += ivar->getContainingInterface()->getNameAsString();
5135 if (LangOpts.MicrosoftExt)
5136 Result += "_IMPL";
5137 Result += ", ";
5138 Result += ivar->getNameAsString();
5139 Result += ")";
5140 }
5141}
5142
5143/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5144/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005145/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005146/// char *attributes;
5147/// }
5148
5149/// struct _prop_list_t {
5150/// uint32_t entsize; // sizeof(struct _prop_t)
5151/// uint32_t count_of_properties;
5152/// struct _prop_t prop_list[count_of_properties];
5153/// }
5154
5155/// struct _protocol_t;
5156
5157/// struct _protocol_list_t {
5158/// long protocol_count; // Note, this is 32/64 bit
5159/// struct _protocol_t * protocol_list[protocol_count];
5160/// }
5161
5162/// struct _objc_method {
5163/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005164/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005165/// char *_imp;
5166/// }
5167
5168/// struct _method_list_t {
5169/// uint32_t entsize; // sizeof(struct _objc_method)
5170/// uint32_t method_count;
5171/// struct _objc_method method_list[method_count];
5172/// }
5173
5174/// struct _protocol_t {
5175/// id isa; // NULL
5176/// const char * const protocol_name;
5177/// const struct _protocol_list_t * protocol_list; // super protocols
5178/// const struct method_list_t * const instance_methods;
5179/// const struct method_list_t * const class_methods;
5180/// const struct method_list_t *optionalInstanceMethods;
5181/// const struct method_list_t *optionalClassMethods;
5182/// const struct _prop_list_t * properties;
5183/// const uint32_t size; // sizeof(struct _protocol_t)
5184/// const uint32_t flags; // = 0
5185/// const char ** extendedMethodTypes;
5186/// }
5187
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005188/// struct _ivar_t {
5189/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005190/// const char *name;
5191/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005192/// uint32_t alignment;
5193/// uint32_t size;
5194/// }
5195
5196/// struct _ivar_list_t {
5197/// uint32 entsize; // sizeof(struct _ivar_t)
5198/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005199/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005200/// }
5201
5202/// struct _class_ro_t {
5203/// uint32_t const flags;
5204/// uint32_t const instanceStart;
5205/// uint32_t const instanceSize;
5206/// uint32_t const reserved; // only when building for 64bit targets
5207/// const uint8_t * const ivarLayout;
5208/// const char *const name;
5209/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian0a525342012-02-14 19:31:35 +00005210/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005211/// const struct _ivar_list_t *const ivars;
5212/// const uint8_t * const weakIvarLayout;
5213/// const struct _prop_list_t * const properties;
5214/// }
5215
5216/// struct _class_t {
5217/// struct _class_t *isa;
5218/// struct _class_t * const superclass;
5219/// void *cache;
5220/// IMP *vtable;
5221/// struct class_ro_t *ro;
5222/// }
5223
5224/// struct _category_t {
5225/// const char * const name;
5226/// struct _class_t *const cls;
5227/// const struct _method_list_t * const instance_methods;
5228/// const struct _method_list_t * const class_methods;
5229/// const struct _protocol_list_t * const protocols;
5230/// const struct _prop_list_t * const properties;
5231/// }
5232
5233/// MessageRefTy - LLVM for:
5234/// struct _message_ref_t {
5235/// IMP messenger;
5236/// SEL name;
5237/// };
5238
5239/// SuperMessageRefTy - LLVM for:
5240/// struct _super_message_ref_t {
5241/// SUPER_IMP messenger;
5242/// SEL name;
5243/// };
5244
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005245static void WriteModernMetadataDeclarations(std::string &Result) {
5246 static bool meta_data_declared = false;
5247 if (meta_data_declared)
5248 return;
5249
5250 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005251 Result += "\tconst char *name;\n";
5252 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005253 Result += "};\n";
5254
5255 Result += "\nstruct _protocol_t;\n";
5256
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005257 Result += "\nstruct _objc_method {\n";
5258 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005259 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005260 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005261 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005262
5263 Result += "\nstruct _protocol_t {\n";
5264 Result += "\tvoid * isa; // NULL\n";
5265 Result += "\tconst char * const protocol_name;\n";
5266 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5267 Result += "\tconst struct method_list_t * const instance_methods;\n";
5268 Result += "\tconst struct method_list_t * const class_methods;\n";
5269 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5270 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5271 Result += "\tconst struct _prop_list_t * properties;\n";
5272 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5273 Result += "\tconst unsigned int flags; // = 0\n";
5274 Result += "\tconst char ** extendedMethodTypes;\n";
5275 Result += "};\n";
5276
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005277 Result += "\nstruct _ivar_t {\n";
5278 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005279 Result += "\tconst char *name;\n";
5280 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005281 Result += "\tunsigned int alignment;\n";
5282 Result += "\tunsigned int size;\n";
5283 Result += "};\n";
5284
5285 Result += "\nstruct _class_ro_t {\n";
5286 Result += "\tunsigned int const flags;\n";
5287 Result += "\tunsigned int instanceStart;\n";
5288 Result += "\tunsigned int const instanceSize;\n";
5289 Result += "\tunsigned int const reserved; // only when building for 64bit targets\n";
5290 Result += "\tconst unsigned char * const ivarLayout;\n";
5291 Result += "\tconst char *const name;\n";
5292 Result += "\tconst struct _method_list_t * const baseMethods;\n";
5293 Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n";
5294 Result += "\tconst struct _ivar_list_t *const ivars;\n";
5295 Result += "\tconst unsigned char *const weakIvarLayout;\n";
5296 Result += "\tconst struct _prop_list_t *const properties;\n";
5297 Result += "};\n";
5298
5299 Result += "\nstruct _class_t {\n";
5300 Result += "\tstruct _class_t *isa;\n";
5301 Result += "\tstruct _class_t *const superclass;\n";
5302 Result += "\tvoid *cache;\n";
5303 Result += "\tvoid *vtable;\n";
5304 Result += "\tstruct class_ro_t *ro;\n";
5305 Result += "};\n";
5306
5307 Result += "\nstruct _category_t {\n";
5308 Result += "\tconst char * const name;\n";
5309 Result += "\tstruct _class_t *const cls;\n";
5310 Result += "\tconst struct _method_list_t *const instance_methods;\n";
5311 Result += "\tconst struct _method_list_t *const class_methods;\n";
5312 Result += "\tconst struct _protocol_list_t *const protocols;\n";
5313 Result += "\tconst struct _prop_list_t *const properties;\n";
5314 Result += "};\n";
5315
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005316 meta_data_declared = true;
5317}
5318
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005319static void Write_protocol_list_t_TypeDecl(std::string &Result,
5320 long super_protocol_count) {
5321 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5322 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5323 Result += "\tstruct _protocol_t *super_protocols[";
5324 Result += utostr(super_protocol_count); Result += "];\n";
5325 Result += "}";
5326}
5327
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005328static void Write_method_list_t_TypeDecl(std::string &Result,
5329 unsigned int method_count) {
5330 Result += "struct /*_method_list_t*/"; Result += " {\n";
5331 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5332 Result += "\tunsigned int method_count;\n";
5333 Result += "\tstruct _objc_method method_list[";
5334 Result += utostr(method_count); Result += "];\n";
5335 Result += "}";
5336}
5337
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005338static void Write__prop_list_t_TypeDecl(std::string &Result,
5339 unsigned int property_count) {
5340 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5341 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5342 Result += "\tunsigned int count_of_properties;\n";
5343 Result += "\tstruct _prop_t prop_list[";
5344 Result += utostr(property_count); Result += "];\n";
5345 Result += "}";
5346}
5347
Fariborz Jahanianae932952012-02-10 20:47:10 +00005348static void Write__ivar_list_t_TypeDecl(std::string &Result,
5349 unsigned int ivar_count) {
5350 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5351 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5352 Result += "\tunsigned int count;\n";
5353 Result += "\tstruct _ivar_t ivar_list[";
5354 Result += utostr(ivar_count); Result += "];\n";
5355 Result += "}";
5356}
5357
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005358static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5359 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5360 StringRef VarName,
5361 StringRef ProtocolName) {
5362 if (SuperProtocols.size() > 0) {
5363 Result += "\nstatic ";
5364 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5365 Result += " "; Result += VarName;
5366 Result += ProtocolName;
5367 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5368 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5369 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5370 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5371 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5372 Result += SuperPD->getNameAsString();
5373 if (i == e-1)
5374 Result += "\n};\n";
5375 else
5376 Result += ",\n";
5377 }
5378 }
5379}
5380
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005381static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5382 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005383 ArrayRef<ObjCMethodDecl *> Methods,
5384 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005385 StringRef TopLevelDeclName,
5386 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005387 if (Methods.size() > 0) {
5388 Result += "\nstatic ";
5389 Write_method_list_t_TypeDecl(Result, Methods.size());
5390 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005391 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005392 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5393 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5394 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5395 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5396 ObjCMethodDecl *MD = Methods[i];
5397 if (i == 0)
5398 Result += "\t{{(struct objc_selector *)\"";
5399 else
5400 Result += "\t{(struct objc_selector *)\"";
5401 Result += (MD)->getSelector().getAsString(); Result += "\"";
5402 Result += ", ";
5403 std::string MethodTypeString;
5404 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5405 Result += "\""; Result += MethodTypeString; Result += "\"";
5406 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005407 if (!MethodImpl)
5408 Result += "0";
5409 else {
5410 Result += "(void *)";
5411 Result += RewriteObj.MethodInternalNames[MD];
5412 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005413 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005414 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005415 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005416 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005417 }
5418 Result += "};\n";
5419 }
5420}
5421
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005422static void Write__prop_list_t_initializer(RewriteModernObjC &RewriteObj,
5423 ASTContext *Context, std::string &Result,
5424 ArrayRef<ObjCPropertyDecl *> Properties,
5425 const Decl *Container,
5426 StringRef VarName,
5427 StringRef ProtocolName) {
5428 if (Properties.size() > 0) {
5429 Result += "\nstatic ";
5430 Write__prop_list_t_TypeDecl(Result, Properties.size());
5431 Result += " "; Result += VarName;
5432 Result += ProtocolName;
5433 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5434 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5435 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5436 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5437 ObjCPropertyDecl *PropDecl = Properties[i];
5438 if (i == 0)
5439 Result += "\t{{\"";
5440 else
5441 Result += "\t{\"";
5442 Result += PropDecl->getName(); Result += "\",";
5443 std::string PropertyTypeString, QuotePropertyTypeString;
5444 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5445 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5446 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5447 if (i == e-1)
5448 Result += "}}\n";
5449 else
5450 Result += "},\n";
5451 }
5452 Result += "};\n";
5453 }
5454}
5455
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005456static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5457 ASTContext *Context, std::string &Result,
5458 ArrayRef<ObjCMethodDecl *> Methods,
5459 StringRef VarName,
5460 StringRef ProtocolName) {
5461 if (Methods.size() == 0)
5462 return;
5463
5464 Result += "\nstatic const char *";
5465 Result += VarName; Result += ProtocolName;
5466 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5467 Result += "{\n";
5468 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5469 ObjCMethodDecl *MD = Methods[i];
5470 std::string MethodTypeString, QuoteMethodTypeString;
5471 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5472 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5473 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5474 if (i == e-1)
5475 Result += "\n};\n";
5476 else {
5477 Result += ",\n";
5478 }
5479 }
5480}
5481
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005482static void Write_IvarOffsetVar(std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005483 ArrayRef<ObjCIvarDecl *> Ivars,
5484 StringRef VarName,
5485 StringRef ClassName) {
5486 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5487 // this is what happens:
5488 /**
5489 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5490 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5491 Class->getVisibility() == HiddenVisibility)
5492 Visibility shoud be: HiddenVisibility;
5493 else
5494 Visibility shoud be: DefaultVisibility;
5495 */
5496
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005497 Result += "\n";
5498 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5499 ObjCIvarDecl *IvarDecl = Ivars[i];
5500 Result += "unsigned long int "; Result += VarName;
5501 Result += ClassName; Result += "_";
5502 Result += IvarDecl->getName();
5503 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5504 Result += " = ";
5505 if (IvarDecl->isBitField()) {
5506 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5507 // place all bitfields at offset 0.
5508 Result += "0;\n";
5509 }
5510 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005511 Result += "__OFFSETOFIVAR__(struct ";
5512 Result += ClassName;
5513 Result += "_IMPL, ";
5514 Result += IvarDecl->getName(); Result += ");\n";
5515 }
5516 }
5517}
5518
Fariborz Jahanianae932952012-02-10 20:47:10 +00005519static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5520 ASTContext *Context, std::string &Result,
5521 ArrayRef<ObjCIvarDecl *> Ivars,
5522 StringRef VarName,
5523 StringRef ClassName) {
5524 if (Ivars.size() > 0) {
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005525 Write_IvarOffsetVar(Result, Ivars, "OBJC_IVAR_$_", ClassName);
5526
Fariborz Jahanianae932952012-02-10 20:47:10 +00005527 Result += "\nstatic ";
5528 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5529 Result += " "; Result += VarName;
5530 Result += ClassName;
5531 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5532 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5533 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5534 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5535 ObjCIvarDecl *IvarDecl = Ivars[i];
5536 if (i == 0)
5537 Result += "\t{{";
5538 else
5539 Result += "\t {";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005540
5541 Result += "(unsigned long int *)&OBJC_IVAR_$_";
5542 Result += ClassName; Result += "_"; Result += IvarDecl->getName();
5543 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005544
5545 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5546 std::string IvarTypeString, QuoteIvarTypeString;
5547 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5548 IvarDecl);
5549 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5550 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5551
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005552 // FIXME. this alignment represents the host alignment and need be changed to
5553 // represent the target alignment.
5554 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5555 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005556 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005557 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5558 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005559 if (i == e-1)
5560 Result += "}}\n";
5561 else
5562 Result += "},\n";
5563 }
5564 Result += "};\n";
5565 }
5566}
5567
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005568/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005569void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5570 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005571
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005572 // Do not synthesize the protocol more than once.
5573 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5574 return;
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005575 WriteModernMetadataDeclarations(Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005576
5577 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5578 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005579 // Must write out all protocol definitions in current qualifier list,
5580 // and in their nested qualifiers before writing out current definition.
5581 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5582 E = PDecl->protocol_end(); I != E; ++I)
5583 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005584
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005585 // Construct method lists.
5586 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5587 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5588 for (ObjCProtocolDecl::instmeth_iterator
5589 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5590 I != E; ++I) {
5591 ObjCMethodDecl *MD = *I;
5592 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5593 OptInstanceMethods.push_back(MD);
5594 } else {
5595 InstanceMethods.push_back(MD);
5596 }
5597 }
5598
5599 for (ObjCProtocolDecl::classmeth_iterator
5600 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5601 I != E; ++I) {
5602 ObjCMethodDecl *MD = *I;
5603 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5604 OptClassMethods.push_back(MD);
5605 } else {
5606 ClassMethods.push_back(MD);
5607 }
5608 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005609 std::vector<ObjCMethodDecl *> AllMethods;
5610 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5611 AllMethods.push_back(InstanceMethods[i]);
5612 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5613 AllMethods.push_back(ClassMethods[i]);
5614 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5615 AllMethods.push_back(OptInstanceMethods[i]);
5616 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5617 AllMethods.push_back(OptClassMethods[i]);
5618
5619 Write__extendedMethodTypes_initializer(*this, Context, Result,
5620 AllMethods,
5621 "_OBJC_PROTOCOL_METHOD_TYPES_",
5622 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005623 // Protocol's super protocol list
5624 std::vector<ObjCProtocolDecl *> SuperProtocols;
5625 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5626 E = PDecl->protocol_end(); I != E; ++I)
5627 SuperProtocols.push_back(*I);
5628
5629 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5630 "_OBJC_PROTOCOL_REFS_",
5631 PDecl->getNameAsString());
5632
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005633 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005634 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005635 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005636
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005637 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005638 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005639 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005640
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005641 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005642 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005643 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005644
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005645 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005646 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005647 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005648
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005649 // Protocol's property metadata.
5650 std::vector<ObjCPropertyDecl *> ProtocolProperties;
5651 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
5652 E = PDecl->prop_end(); I != E; ++I)
5653 ProtocolProperties.push_back(*I);
5654
5655 Write__prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
5656 /* Container */0,
5657 "_OBJC_PROTOCOL_PROPERTIES_",
5658 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005659
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005660 // Writer out root metadata for current protocol: struct _protocol_t
5661 Result += "\nstatic struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005662 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005663 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
5664 Result += "\t0,\n"; // id is; is null
5665 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005666 if (SuperProtocols.size() > 0) {
5667 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
5668 Result += PDecl->getNameAsString(); Result += ",\n";
5669 }
5670 else
5671 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005672 if (InstanceMethods.size() > 0) {
5673 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5674 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005675 }
5676 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005677 Result += "\t0,\n";
5678
5679 if (ClassMethods.size() > 0) {
5680 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5681 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005682 }
5683 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005684 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005685
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005686 if (OptInstanceMethods.size() > 0) {
5687 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
5688 Result += PDecl->getNameAsString(); Result += ",\n";
5689 }
5690 else
5691 Result += "\t0,\n";
5692
5693 if (OptClassMethods.size() > 0) {
5694 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
5695 Result += PDecl->getNameAsString(); Result += ",\n";
5696 }
5697 else
5698 Result += "\t0,\n";
5699
5700 if (ProtocolProperties.size() > 0) {
5701 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
5702 Result += PDecl->getNameAsString(); Result += ",\n";
5703 }
5704 else
5705 Result += "\t0,\n";
5706
5707 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
5708 Result += "\t0,\n";
5709
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005710 if (AllMethods.size() > 0) {
5711 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
5712 Result += PDecl->getNameAsString();
5713 Result += "\n};\n";
5714 }
5715 else
5716 Result += "\t0\n};\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005717
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005718 // Mark this protocol as having been generated.
5719 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
5720 llvm_unreachable("protocol already synthesized");
5721
5722}
5723
5724void RewriteModernObjC::RewriteObjCProtocolListMetaData(
5725 const ObjCList<ObjCProtocolDecl> &Protocols,
5726 StringRef prefix, StringRef ClassName,
5727 std::string &Result) {
5728 if (Protocols.empty()) return;
5729
5730 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005731 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005732
5733 // Output the top lovel protocol meta-data for the class.
5734 /* struct _objc_protocol_list {
5735 struct _objc_protocol_list *next;
5736 int protocol_count;
5737 struct _objc_protocol *class_protocols[];
5738 }
5739 */
5740 Result += "\nstatic struct {\n";
5741 Result += "\tstruct _objc_protocol_list *next;\n";
5742 Result += "\tint protocol_count;\n";
5743 Result += "\tstruct _objc_protocol *class_protocols[";
5744 Result += utostr(Protocols.size());
5745 Result += "];\n} _OBJC_";
5746 Result += prefix;
5747 Result += "_PROTOCOLS_";
5748 Result += ClassName;
5749 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5750 "{\n\t0, ";
5751 Result += utostr(Protocols.size());
5752 Result += "\n";
5753
5754 Result += "\t,{&_OBJC_PROTOCOL_";
5755 Result += Protocols[0]->getNameAsString();
5756 Result += " \n";
5757
5758 for (unsigned i = 1; i != Protocols.size(); i++) {
5759 Result += "\t ,&_OBJC_PROTOCOL_";
5760 Result += Protocols[i]->getNameAsString();
5761 Result += "\n";
5762 }
5763 Result += "\t }\n};\n";
5764}
5765
5766void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5767 std::string &Result) {
5768 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5769
5770 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00005771 if (CDecl->isImplicitInterfaceDecl())
5772 assert(false &&
5773 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005774
Fariborz Jahanianae932952012-02-10 20:47:10 +00005775 WriteModernMetadataDeclarations(Result);
5776 SmallVector<ObjCIvarDecl *, 8> IVars;
5777
5778 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
5779 IVD; IVD = IVD->getNextIvar()) {
5780 // Ignore unnamed bit-fields.
5781 if (!IVD->getDeclName())
5782 continue;
5783 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005784 }
5785
Fariborz Jahanianae932952012-02-10 20:47:10 +00005786 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
5787 "_OBJC_INSTANCE_VARIABLES_",
5788 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005789
5790 // Build _objc_method_list for class's instance methods if needed
5791 SmallVector<ObjCMethodDecl *, 32>
5792 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5793
5794 // If any of our property implementations have associated getters or
5795 // setters, produce metadata for them as well.
5796 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5797 PropEnd = IDecl->propimpl_end();
5798 Prop != PropEnd; ++Prop) {
5799 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5800 continue;
5801 if (!(*Prop)->getPropertyIvarDecl())
5802 continue;
5803 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5804 if (!PD)
5805 continue;
5806 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5807 if (!Getter->isDefined())
5808 InstanceMethods.push_back(Getter);
5809 if (PD->isReadOnly())
5810 continue;
5811 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5812 if (!Setter->isDefined())
5813 InstanceMethods.push_back(Setter);
5814 }
5815
5816 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
5817 "_OBJC_$_INSTANCE_METHODS_",
5818 IDecl->getNameAsString(), true);
5819
5820 SmallVector<ObjCMethodDecl *, 32>
5821 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
5822
5823 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
5824 "_OBJC_$_CLASS_METHODS_",
5825 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00005826
5827 // Protocols referenced in class declaration?
5828 // Protocol's super protocol list
5829 std::vector<ObjCProtocolDecl *> RefedProtocols;
5830 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
5831 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
5832 E = Protocols.end();
5833 I != E; ++I) {
5834 RefedProtocols.push_back(*I);
5835 // Must write out all protocol definitions in current qualifier list,
5836 // and in their nested qualifiers before writing out current definition.
5837 RewriteObjCProtocolMetaData(*I, Result);
5838 }
5839
5840 Write_protocol_list_initializer(Context, Result,
5841 RefedProtocols,
5842 "_OBJC_CLASS_PROTOCOLS_$_",
5843 IDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005844
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005845}
5846
5847void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
5848 int ClsDefCount = ClassImplementation.size();
5849 int CatDefCount = CategoryImplementation.size();
5850
5851 // For each implemented class, write out all its meta data.
5852 for (int i = 0; i < ClsDefCount; i++)
5853 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5854
5855 // For each implemented category, write out all its meta data.
5856 for (int i = 0; i < CatDefCount; i++)
5857 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5858
5859 // Write objc_symtab metadata
5860 /*
5861 struct _objc_symtab
5862 {
5863 long sel_ref_cnt;
5864 SEL *refs;
5865 short cls_def_cnt;
5866 short cat_def_cnt;
5867 void *defs[cls_def_cnt + cat_def_cnt];
5868 };
5869 */
5870
5871 Result += "\nstruct _objc_symtab {\n";
5872 Result += "\tlong sel_ref_cnt;\n";
5873 Result += "\tSEL *refs;\n";
5874 Result += "\tshort cls_def_cnt;\n";
5875 Result += "\tshort cat_def_cnt;\n";
5876 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5877 Result += "};\n\n";
5878
5879 Result += "static struct _objc_symtab "
5880 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5881 Result += "\t0, 0, " + utostr(ClsDefCount)
5882 + ", " + utostr(CatDefCount) + "\n";
5883 for (int i = 0; i < ClsDefCount; i++) {
5884 Result += "\t,&_OBJC_CLASS_";
5885 Result += ClassImplementation[i]->getNameAsString();
5886 Result += "\n";
5887 }
5888
5889 for (int i = 0; i < CatDefCount; i++) {
5890 Result += "\t,&_OBJC_CATEGORY_";
5891 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5892 Result += "_";
5893 Result += CategoryImplementation[i]->getNameAsString();
5894 Result += "\n";
5895 }
5896
5897 Result += "};\n\n";
5898
5899 // Write objc_module metadata
5900
5901 /*
5902 struct _objc_module {
5903 long version;
5904 long size;
5905 const char *name;
5906 struct _objc_symtab *symtab;
5907 }
5908 */
5909
5910 Result += "\nstruct _objc_module {\n";
5911 Result += "\tlong version;\n";
5912 Result += "\tlong size;\n";
5913 Result += "\tconst char *name;\n";
5914 Result += "\tstruct _objc_symtab *symtab;\n";
5915 Result += "};\n\n";
5916 Result += "static struct _objc_module "
5917 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5918 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5919 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5920 Result += "};\n\n";
5921
5922 if (LangOpts.MicrosoftExt) {
5923 if (ProtocolExprDecls.size()) {
5924 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5925 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5926 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5927 E = ProtocolExprDecls.end(); I != E; ++I) {
5928 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5929 Result += (*I)->getNameAsString();
5930 Result += " = &_OBJC_PROTOCOL_";
5931 Result += (*I)->getNameAsString();
5932 Result += ";\n";
5933 }
5934 Result += "#pragma data_seg(pop)\n\n";
5935 }
5936 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5937 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5938 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5939 Result += "&_OBJC_MODULES;\n";
5940 Result += "#pragma data_seg(pop)\n\n";
5941 }
5942}
5943
5944/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5945/// implementation.
5946void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5947 std::string &Result) {
5948 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5949 // Find category declaration for this implementation.
5950 ObjCCategoryDecl *CDecl;
5951 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5952 CDecl = CDecl->getNextClassCategory())
5953 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5954 break;
5955
5956 std::string FullCategoryName = ClassDecl->getNameAsString();
5957 FullCategoryName += '_';
5958 FullCategoryName += IDecl->getNameAsString();
5959
5960 // Build _objc_method_list for class's instance methods if needed
5961 SmallVector<ObjCMethodDecl *, 32>
5962 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5963
5964 // If any of our property implementations have associated getters or
5965 // setters, produce metadata for them as well.
5966 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5967 PropEnd = IDecl->propimpl_end();
5968 Prop != PropEnd; ++Prop) {
5969 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5970 continue;
5971 if (!(*Prop)->getPropertyIvarDecl())
5972 continue;
5973 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5974 if (!PD)
5975 continue;
5976 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5977 InstanceMethods.push_back(Getter);
5978 if (PD->isReadOnly())
5979 continue;
5980 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5981 InstanceMethods.push_back(Setter);
5982 }
5983 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5984 true, "CATEGORY_", FullCategoryName.c_str(),
5985 Result);
5986
5987 // Build _objc_method_list for class's class methods if needed
5988 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5989 false, "CATEGORY_", FullCategoryName.c_str(),
5990 Result);
5991
5992 // Protocols referenced in class declaration?
5993 // Null CDecl is case of a category implementation with no category interface
5994 if (CDecl)
5995 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5996 FullCategoryName, Result);
5997 /* struct _objc_category {
5998 char *category_name;
5999 char *class_name;
6000 struct _objc_method_list *instance_methods;
6001 struct _objc_method_list *class_methods;
6002 struct _objc_protocol_list *protocols;
6003 // Objective-C 1.0 extensions
6004 uint32_t size; // sizeof (struct _objc_category)
6005 struct _objc_property_list *instance_properties; // category's own
6006 // @property decl.
6007 };
6008 */
6009
6010 static bool objc_category = false;
6011 if (!objc_category) {
6012 Result += "\nstruct _objc_category {\n";
6013 Result += "\tchar *category_name;\n";
6014 Result += "\tchar *class_name;\n";
6015 Result += "\tstruct _objc_method_list *instance_methods;\n";
6016 Result += "\tstruct _objc_method_list *class_methods;\n";
6017 Result += "\tstruct _objc_protocol_list *protocols;\n";
6018 Result += "\tunsigned int size;\n";
6019 Result += "\tstruct _objc_property_list *instance_properties;\n";
6020 Result += "};\n";
6021 objc_category = true;
6022 }
6023 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
6024 Result += FullCategoryName;
6025 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
6026 Result += IDecl->getNameAsString();
6027 Result += "\"\n\t, \"";
6028 Result += ClassDecl->getNameAsString();
6029 Result += "\"\n";
6030
6031 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
6032 Result += "\t, (struct _objc_method_list *)"
6033 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
6034 Result += FullCategoryName;
6035 Result += "\n";
6036 }
6037 else
6038 Result += "\t, 0\n";
6039 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
6040 Result += "\t, (struct _objc_method_list *)"
6041 "&_OBJC_CATEGORY_CLASS_METHODS_";
6042 Result += FullCategoryName;
6043 Result += "\n";
6044 }
6045 else
6046 Result += "\t, 0\n";
6047
6048 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
6049 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
6050 Result += FullCategoryName;
6051 Result += "\n";
6052 }
6053 else
6054 Result += "\t, 0\n";
6055 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
6056}
6057
6058// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6059/// class methods.
6060template<typename MethodIterator>
6061void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6062 MethodIterator MethodEnd,
6063 bool IsInstanceMethod,
6064 StringRef prefix,
6065 StringRef ClassName,
6066 std::string &Result) {
6067 if (MethodBegin == MethodEnd) return;
6068
6069 if (!objc_impl_method) {
6070 /* struct _objc_method {
6071 SEL _cmd;
6072 char *method_types;
6073 void *_imp;
6074 }
6075 */
6076 Result += "\nstruct _objc_method {\n";
6077 Result += "\tSEL _cmd;\n";
6078 Result += "\tchar *method_types;\n";
6079 Result += "\tvoid *_imp;\n";
6080 Result += "};\n";
6081
6082 objc_impl_method = true;
6083 }
6084
6085 // Build _objc_method_list for class's methods if needed
6086
6087 /* struct {
6088 struct _objc_method_list *next_method;
6089 int method_count;
6090 struct _objc_method method_list[];
6091 }
6092 */
6093 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
6094 Result += "\nstatic struct {\n";
6095 Result += "\tstruct _objc_method_list *next_method;\n";
6096 Result += "\tint method_count;\n";
6097 Result += "\tstruct _objc_method method_list[";
6098 Result += utostr(NumMethods);
6099 Result += "];\n} _OBJC_";
6100 Result += prefix;
6101 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6102 Result += "_METHODS_";
6103 Result += ClassName;
6104 Result += " __attribute__ ((used, section (\"__OBJC, __";
6105 Result += IsInstanceMethod ? "inst" : "cls";
6106 Result += "_meth\")))= ";
6107 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6108
6109 Result += "\t,{{(SEL)\"";
6110 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6111 std::string MethodTypeString;
6112 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6113 Result += "\", \"";
6114 Result += MethodTypeString;
6115 Result += "\", (void *)";
6116 Result += MethodInternalNames[*MethodBegin];
6117 Result += "}\n";
6118 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6119 Result += "\t ,{(SEL)\"";
6120 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6121 std::string MethodTypeString;
6122 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6123 Result += "\", \"";
6124 Result += MethodTypeString;
6125 Result += "\", (void *)";
6126 Result += MethodInternalNames[*MethodBegin];
6127 Result += "}\n";
6128 }
6129 Result += "\t }\n};\n";
6130}
6131
6132Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6133 SourceRange OldRange = IV->getSourceRange();
6134 Expr *BaseExpr = IV->getBase();
6135
6136 // Rewrite the base, but without actually doing replaces.
6137 {
6138 DisableReplaceStmtScope S(*this);
6139 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6140 IV->setBase(BaseExpr);
6141 }
6142
6143 ObjCIvarDecl *D = IV->getDecl();
6144
6145 Expr *Replacement = IV;
6146 if (CurMethodDef) {
6147 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6148 const ObjCInterfaceType *iFaceDecl =
6149 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6150 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6151 // lookup which class implements the instance variable.
6152 ObjCInterfaceDecl *clsDeclared = 0;
6153 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6154 clsDeclared);
6155 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6156
6157 // Synthesize an explicit cast to gain access to the ivar.
6158 std::string RecName = clsDeclared->getIdentifier()->getName();
6159 RecName += "_IMPL";
6160 IdentifierInfo *II = &Context->Idents.get(RecName);
6161 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6162 SourceLocation(), SourceLocation(),
6163 II);
6164 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6165 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6166 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6167 CK_BitCast,
6168 IV->getBase());
6169 // Don't forget the parens to enforce the proper binding.
6170 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
6171 OldRange.getEnd(),
6172 castExpr);
6173 if (IV->isFreeIvar() &&
6174 declaresSameEntity(CurMethodDef->getClassInterface(), iFaceDecl->getDecl())) {
6175 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
6176 IV->getLocation(),
6177 D->getType(),
6178 VK_LValue, OK_Ordinary);
6179 Replacement = ME;
6180 } else {
6181 IV->setBase(PE);
6182 }
6183 }
6184 } else { // we are outside a method.
6185 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
6186
6187 // Explicit ivar refs need to have a cast inserted.
6188 // FIXME: consider sharing some of this code with the code above.
6189 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6190 const ObjCInterfaceType *iFaceDecl =
6191 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6192 // lookup which class implements the instance variable.
6193 ObjCInterfaceDecl *clsDeclared = 0;
6194 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6195 clsDeclared);
6196 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6197
6198 // Synthesize an explicit cast to gain access to the ivar.
6199 std::string RecName = clsDeclared->getIdentifier()->getName();
6200 RecName += "_IMPL";
6201 IdentifierInfo *II = &Context->Idents.get(RecName);
6202 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
6203 SourceLocation(), SourceLocation(),
6204 II);
6205 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
6206 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
6207 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
6208 CK_BitCast,
6209 IV->getBase());
6210 // Don't forget the parens to enforce the proper binding.
6211 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
6212 IV->getBase()->getLocEnd(), castExpr);
6213 // Cannot delete IV->getBase(), since PE points to it.
6214 // Replace the old base with the cast. This is important when doing
6215 // embedded rewrites. For example, [newInv->_container addObject:0].
6216 IV->setBase(PE);
6217 }
6218 }
6219
6220 ReplaceStmtWithRange(IV, Replacement, OldRange);
6221 return Replacement;
6222}
6223