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