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