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