1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 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 // This coordinates the per-module state used while generating code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGDebugInfo.h" 15 #include "CodeGenModule.h" 16 #include "CodeGenFunction.h" 17 #include "CGCall.h" 18 #include "CGObjCRuntime.h" 19 #include "Mangle.h" 20 #include "clang/AST/ASTContext.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/Basic/Diagnostic.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "llvm/CallingConv.h" 27 #include "llvm/Module.h" 28 #include "llvm/Intrinsics.h" 29 #include "llvm/Target/TargetData.h" 30 using namespace clang; 31 using namespace CodeGen; 32 33 34 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO, 35 llvm::Module &M, const llvm::TargetData &TD, 36 Diagnostic &diags, bool GenerateDebugInfo) 37 : BlockModule(C, M, TD, Types, *this), Context(C), Features(LO), TheModule(M), 38 TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0), 39 MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0) { 40 41 if (!Features.ObjC1) 42 Runtime = 0; 43 else if (!Features.NeXTRuntime) 44 Runtime = CreateGNUObjCRuntime(*this); 45 else if (Features.ObjCNonFragileABI) 46 Runtime = CreateMacNonFragileABIObjCRuntime(*this); 47 else 48 Runtime = CreateMacObjCRuntime(*this); 49 50 // If debug info generation is enabled, create the CGDebugInfo object. 51 DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0; 52 } 53 54 CodeGenModule::~CodeGenModule() { 55 delete Runtime; 56 delete DebugInfo; 57 } 58 59 void CodeGenModule::Release() { 60 EmitDeferred(); 61 EmitAliases(); 62 if (Runtime) 63 if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction()) 64 AddGlobalCtor(ObjCInitFunction); 65 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 66 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 67 EmitAnnotations(); 68 EmitLLVMUsed(); 69 BindRuntimeGlobals(); 70 } 71 72 void CodeGenModule::BindRuntimeGlobals() { 73 // Deal with protecting runtime function names. 74 for (unsigned i = 0, e = RuntimeGlobals.size(); i < e; ++i) { 75 llvm::GlobalValue *GV = RuntimeGlobals[i].first; 76 const std::string &Name = RuntimeGlobals[i].second; 77 78 // Discard unused runtime declarations. 79 if (GV->isDeclaration() && GV->use_empty()) { 80 GV->eraseFromParent(); 81 continue; 82 } 83 84 // See if there is a conflict against a function by setting the name and 85 // seeing if we got the desired name. 86 GV->setName(Name); 87 if (GV->isName(Name.c_str())) 88 continue; // Yep, it worked! 89 90 GV->setName(""); // Zap the bogus name until we work out the conflict. 91 llvm::GlobalValue *Conflict = TheModule.getNamedValue(Name); 92 assert(Conflict && "Must have conflicted!"); 93 94 // Decide which version to take. If the conflict is a definition 95 // we are forced to take that, otherwise assume the runtime 96 // knows best. 97 98 // FIXME: This will fail phenomenally when the conflict is the 99 // wrong type of value. Just bail on it for now. This should 100 // really reuse something inside the LLVM Linker code. 101 assert(GV->getValueID() == Conflict->getValueID() && 102 "Unable to resolve conflict between globals of different types."); 103 if (!Conflict->isDeclaration()) { 104 llvm::Value *Casted = 105 llvm::ConstantExpr::getBitCast(Conflict, GV->getType()); 106 GV->replaceAllUsesWith(Casted); 107 GV->eraseFromParent(); 108 } else { 109 GV->takeName(Conflict); 110 llvm::Value *Casted = 111 llvm::ConstantExpr::getBitCast(GV, Conflict->getType()); 112 Conflict->replaceAllUsesWith(Casted); 113 Conflict->eraseFromParent(); 114 } 115 } 116 } 117 118 /// ErrorUnsupported - Print out an error that codegen doesn't support the 119 /// specified stmt yet. 120 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type, 121 bool OmitOnError) { 122 if (OmitOnError && getDiags().hasErrorOccurred()) 123 return; 124 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 125 "cannot compile this %0 yet"); 126 std::string Msg = Type; 127 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID) 128 << Msg << S->getSourceRange(); 129 } 130 131 /// ErrorUnsupported - Print out an error that codegen doesn't support the 132 /// specified decl yet. 133 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type, 134 bool OmitOnError) { 135 if (OmitOnError && getDiags().hasErrorOccurred()) 136 return; 137 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error, 138 "cannot compile this %0 yet"); 139 std::string Msg = Type; 140 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 141 } 142 143 /// setGlobalVisibility - Set the visibility for the given LLVM 144 /// GlobalValue according to the given clang AST visibility value. 145 static void setGlobalVisibility(llvm::GlobalValue *GV, 146 VisibilityAttr::VisibilityTypes Vis) { 147 switch (Vis) { 148 default: assert(0 && "Unknown visibility!"); 149 case VisibilityAttr::DefaultVisibility: 150 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 151 break; 152 case VisibilityAttr::HiddenVisibility: 153 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 154 break; 155 case VisibilityAttr::ProtectedVisibility: 156 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 157 break; 158 } 159 } 160 161 /// \brief Retrieves the mangled name for the given declaration. 162 /// 163 /// If the given declaration requires a mangled name, returns an 164 /// const char* containing the mangled name. Otherwise, returns 165 /// the unmangled name. 166 /// 167 /// FIXME: Returning an IdentifierInfo* here is a total hack. We 168 /// really need some kind of string abstraction that either stores a 169 /// mangled name or stores an IdentifierInfo*. This will require 170 /// changes to the GlobalDeclMap, too. (I disagree, I think what we 171 /// actually need is for Sema to provide some notion of which Decls 172 /// refer to the same semantic decl. We shouldn't need to mangle the 173 /// names and see what comes out the same to figure this out. - DWD) 174 /// 175 /// FIXME: Performance here is going to be terribly until we start 176 /// caching mangled names. However, we should fix the problem above 177 /// first. 178 const char *CodeGenModule::getMangledName(const NamedDecl *ND) { 179 // In C, functions with no attributes never need to be mangled. Fastpath them. 180 if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) { 181 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 182 return ND->getNameAsCString(); 183 } 184 185 llvm::SmallString<256> Name; 186 llvm::raw_svector_ostream Out(Name); 187 if (!mangleName(ND, Context, Out)) { 188 assert(ND->getIdentifier() && "Attempt to mangle unnamed decl."); 189 return ND->getNameAsCString(); 190 } 191 192 Name += '\0'; 193 return MangledNames.GetOrCreateValue(Name.begin(), Name.end()).getKeyData(); 194 } 195 196 /// AddGlobalCtor - Add a function to the list that will be called before 197 /// main() runs. 198 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) { 199 // FIXME: Type coercion of void()* types. 200 GlobalCtors.push_back(std::make_pair(Ctor, Priority)); 201 } 202 203 /// AddGlobalDtor - Add a function to the list that will be called 204 /// when the module is unloaded. 205 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) { 206 // FIXME: Type coercion of void()* types. 207 GlobalDtors.push_back(std::make_pair(Dtor, Priority)); 208 } 209 210 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) { 211 // Ctor function type is void()*. 212 llvm::FunctionType* CtorFTy = 213 llvm::FunctionType::get(llvm::Type::VoidTy, 214 std::vector<const llvm::Type*>(), 215 false); 216 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy); 217 218 // Get the type of a ctor entry, { i32, void ()* }. 219 llvm::StructType* CtorStructTy = 220 llvm::StructType::get(llvm::Type::Int32Ty, 221 llvm::PointerType::getUnqual(CtorFTy), NULL); 222 223 // Construct the constructor and destructor arrays. 224 std::vector<llvm::Constant*> Ctors; 225 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 226 std::vector<llvm::Constant*> S; 227 S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false)); 228 S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)); 229 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S)); 230 } 231 232 if (!Ctors.empty()) { 233 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size()); 234 new llvm::GlobalVariable(AT, false, 235 llvm::GlobalValue::AppendingLinkage, 236 llvm::ConstantArray::get(AT, Ctors), 237 GlobalName, 238 &TheModule); 239 } 240 } 241 242 void CodeGenModule::EmitAnnotations() { 243 if (Annotations.empty()) 244 return; 245 246 // Create a new global variable for the ConstantStruct in the Module. 247 llvm::Constant *Array = 248 llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(), 249 Annotations.size()), 250 Annotations); 251 llvm::GlobalValue *gv = 252 new llvm::GlobalVariable(Array->getType(), false, 253 llvm::GlobalValue::AppendingLinkage, Array, 254 "llvm.global.annotations", &TheModule); 255 gv->setSection("llvm.metadata"); 256 } 257 258 void CodeGenModule::SetGlobalValueAttributes(const Decl *D, 259 bool IsInternal, 260 bool IsInline, 261 llvm::GlobalValue *GV, 262 bool ForDefinition) { 263 // FIXME: Set up linkage and many other things. Note, this is a simple 264 // approximation of what we really want. 265 if (!ForDefinition) { 266 // Only a few attributes are set on declarations. 267 if (D->getAttr<DLLImportAttr>()) { 268 // The dllimport attribute is overridden by a subsequent declaration as 269 // dllexport. 270 if (!D->getAttr<DLLExportAttr>()) { 271 // dllimport attribute can be applied only to function decls, not to 272 // definitions. 273 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 274 if (!FD->getBody()) 275 GV->setLinkage(llvm::Function::DLLImportLinkage); 276 } else 277 GV->setLinkage(llvm::Function::DLLImportLinkage); 278 } 279 } else if (D->getAttr<WeakAttr>() || 280 D->getAttr<WeakImportAttr>()) { 281 // "extern_weak" is overloaded in LLVM; we probably should have 282 // separate linkage types for this. 283 GV->setLinkage(llvm::Function::ExternalWeakLinkage); 284 } 285 } else { 286 if (IsInternal) { 287 GV->setLinkage(llvm::Function::InternalLinkage); 288 } else { 289 if (D->getAttr<DLLExportAttr>()) { 290 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 291 // The dllexport attribute is ignored for undefined symbols. 292 if (FD->getBody()) 293 GV->setLinkage(llvm::Function::DLLExportLinkage); 294 } else 295 GV->setLinkage(llvm::Function::DLLExportLinkage); 296 } else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>() || 297 IsInline) 298 GV->setLinkage(llvm::Function::WeakAnyLinkage); 299 } 300 } 301 302 // FIXME: Figure out the relative priority of the attribute, 303 // -fvisibility, and private_extern. 304 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 305 setGlobalVisibility(GV, attr->getVisibility()); 306 // FIXME: else handle -fvisibility 307 308 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 309 GV->setSection(SA->getName()); 310 311 // Only add to llvm.used when we see a definition, otherwise we 312 // might add multiple times or risk the value being replaced by a 313 // subsequent RAUW. 314 if (ForDefinition) { 315 if (D->getAttr<UsedAttr>()) 316 AddUsedGlobal(GV); 317 } 318 } 319 320 void CodeGenModule::SetFunctionAttributes(const Decl *D, 321 const CGFunctionInfo &Info, 322 llvm::Function *F) { 323 AttributeListType AttributeList; 324 ConstructAttributeList(Info, D, AttributeList); 325 326 F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(), 327 AttributeList.size())); 328 329 // Set the appropriate calling convention for the Function. 330 if (D->getAttr<FastCallAttr>()) 331 F->setCallingConv(llvm::CallingConv::X86_FastCall); 332 333 if (D->getAttr<StdCallAttr>()) 334 F->setCallingConv(llvm::CallingConv::X86_StdCall); 335 } 336 337 /// SetFunctionAttributesForDefinition - Set function attributes 338 /// specific to a function definition. 339 void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D, 340 llvm::Function *F) { 341 if (isa<ObjCMethodDecl>(D)) { 342 SetGlobalValueAttributes(D, true, false, F, true); 343 } else { 344 const FunctionDecl *FD = cast<FunctionDecl>(D); 345 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static, 346 FD->isInline(), F, true); 347 } 348 349 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 350 F->addFnAttr(llvm::Attribute::NoUnwind); 351 352 if (D->getAttr<AlwaysInlineAttr>()) 353 F->addFnAttr(llvm::Attribute::AlwaysInline); 354 355 if (D->getAttr<NoinlineAttr>()) 356 F->addFnAttr(llvm::Attribute::NoInline); 357 } 358 359 void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD, 360 llvm::Function *F) { 361 SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F); 362 363 SetFunctionAttributesForDefinition(MD, F); 364 } 365 366 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD, 367 llvm::Function *F) { 368 SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F); 369 370 SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static, 371 FD->isInline(), F, false); 372 } 373 374 375 void CodeGenModule::EmitAliases() { 376 for (unsigned i = 0, e = Aliases.size(); i != e; ++i) { 377 const ValueDecl *D = Aliases[i]; 378 const AliasAttr *AA = D->getAttr<AliasAttr>(); 379 380 // This is something of a hack, if the FunctionDecl got overridden 381 // then its attributes will be moved to the new declaration. In 382 // this case the current decl has no alias attribute, but we will 383 // eventually see it. 384 if (!AA) 385 continue; 386 387 const std::string& aliaseeName = AA->getAliasee(); 388 llvm::GlobalValue *aliasee = getModule().getNamedValue(aliaseeName); 389 if (!aliasee) { 390 // FIXME: This isn't unsupported, this is just an error, which 391 // sema should catch, but... 392 ErrorUnsupported(D, "alias referencing a missing function"); 393 continue; 394 } 395 396 const char *MangledName = getMangledName(D); 397 llvm::GlobalValue *GA = 398 new llvm::GlobalAlias(aliasee->getType(), 399 llvm::Function::ExternalLinkage, 400 MangledName, aliasee, &getModule()); 401 402 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 403 if (Entry) { 404 // If we created a dummy function for this then replace it. 405 GA->takeName(Entry); 406 407 llvm::Value *Casted = 408 llvm::ConstantExpr::getBitCast(GA, Entry->getType()); 409 Entry->replaceAllUsesWith(Casted); 410 Entry->eraseFromParent(); 411 412 Entry = GA; 413 } 414 415 // Alias should never be internal or inline. 416 SetGlobalValueAttributes(D, false, false, GA, true); 417 } 418 } 419 420 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) { 421 assert(!GV->isDeclaration() && 422 "Only globals with definition can force usage."); 423 llvm::Type *i8PTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 424 LLVMUsed.push_back(llvm::ConstantExpr::getBitCast(GV, i8PTy)); 425 } 426 427 void CodeGenModule::EmitLLVMUsed() { 428 // Don't create llvm.used if there is no need. 429 if (LLVMUsed.empty()) 430 return; 431 432 llvm::ArrayType *ATy = llvm::ArrayType::get(LLVMUsed[0]->getType(), 433 LLVMUsed.size()); 434 llvm::GlobalVariable *GV = 435 new llvm::GlobalVariable(ATy, false, 436 llvm::GlobalValue::AppendingLinkage, 437 llvm::ConstantArray::get(ATy, LLVMUsed), 438 "llvm.used", &getModule()); 439 440 GV->setSection("llvm.metadata"); 441 } 442 443 void CodeGenModule::EmitDeferred() { 444 // Emit code for any deferred decl which was used. Since a 445 // previously unused static decl may become used during the 446 // generation of code for a static function, iterate until no 447 // changes are made. 448 bool Changed; 449 do { 450 Changed = false; 451 452 for (std::list<const ValueDecl*>::iterator i = DeferredDecls.begin(), 453 e = DeferredDecls.end(); i != e; ) { 454 const ValueDecl *D = *i; 455 456 // Check if we have used a decl with the same name 457 // FIXME: The AST should have some sort of aggregate decls or 458 // global symbol map. 459 // FIXME: This is missing some important cases. For example, we 460 // need to check for uses in an alias. 461 if (!GlobalDeclMap.count(getMangledName(D))) { 462 ++i; 463 continue; 464 } 465 466 // Emit the definition. 467 EmitGlobalDefinition(D); 468 469 // Erase the used decl from the list. 470 i = DeferredDecls.erase(i); 471 472 // Remember that we made a change. 473 Changed = true; 474 } 475 } while (Changed); 476 } 477 478 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the 479 /// annotation information for a given GlobalValue. The annotation struct is 480 /// {i8 *, i8 *, i8 *, i32}. The first field is a constant expression, the 481 /// GlobalValue being annotated. The second field is the constant string 482 /// created from the AnnotateAttr's annotation. The third field is a constant 483 /// string containing the name of the translation unit. The fourth field is 484 /// the line number in the file of the annotated value declaration. 485 /// 486 /// FIXME: this does not unique the annotation string constants, as llvm-gcc 487 /// appears to. 488 /// 489 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 490 const AnnotateAttr *AA, 491 unsigned LineNo) { 492 llvm::Module *M = &getModule(); 493 494 // get [N x i8] constants for the annotation string, and the filename string 495 // which are the 2nd and 3rd elements of the global annotation structure. 496 const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty); 497 llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true); 498 llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(), 499 true); 500 501 // Get the two global values corresponding to the ConstantArrays we just 502 // created to hold the bytes of the strings. 503 llvm::GlobalValue *annoGV = 504 new llvm::GlobalVariable(anno->getType(), false, 505 llvm::GlobalValue::InternalLinkage, anno, 506 GV->getName() + ".str", M); 507 // translation unit name string, emitted into the llvm.metadata section. 508 llvm::GlobalValue *unitGV = 509 new llvm::GlobalVariable(unit->getType(), false, 510 llvm::GlobalValue::InternalLinkage, unit, ".str", M); 511 512 // Create the ConstantStruct that is the global annotion. 513 llvm::Constant *Fields[4] = { 514 llvm::ConstantExpr::getBitCast(GV, SBP), 515 llvm::ConstantExpr::getBitCast(annoGV, SBP), 516 llvm::ConstantExpr::getBitCast(unitGV, SBP), 517 llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo) 518 }; 519 return llvm::ConstantStruct::get(Fields, 4, false); 520 } 521 522 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) { 523 // Never defer when EmitAllDecls is specified or the decl has 524 // attribute used. 525 if (Features.EmitAllDecls || Global->getAttr<UsedAttr>()) 526 return false; 527 528 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 529 // Constructors and destructors should never be deferred. 530 if (FD->getAttr<ConstructorAttr>() || FD->getAttr<DestructorAttr>()) 531 return false; 532 533 // FIXME: What about inline, and/or extern inline? 534 if (FD->getStorageClass() != FunctionDecl::Static) 535 return false; 536 } else { 537 const VarDecl *VD = cast<VarDecl>(Global); 538 assert(VD->isFileVarDecl() && "Invalid decl"); 539 540 if (VD->getStorageClass() != VarDecl::Static) 541 return false; 542 } 543 544 return true; 545 } 546 547 void CodeGenModule::EmitGlobal(const ValueDecl *Global) { 548 // Aliases are deferred until code for everything else has been 549 // emitted. 550 if (Global->getAttr<AliasAttr>()) { 551 Aliases.push_back(Global); 552 return; 553 } 554 555 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) { 556 // Forward declarations are emitted lazily on first use. 557 if (!FD->isThisDeclarationADefinition()) 558 return; 559 } else { 560 const VarDecl *VD = cast<VarDecl>(Global); 561 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 562 563 // Forward declarations are emitted lazily on first use. 564 if (!VD->getInit() && VD->hasExternalStorage()) 565 return; 566 } 567 568 // Defer code generation when possible. 569 if (MayDeferGeneration(Global)) { 570 DeferredDecls.push_back(Global); 571 return; 572 } 573 574 // Otherwise emit the definition. 575 EmitGlobalDefinition(Global); 576 } 577 578 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) { 579 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 580 EmitGlobalFunctionDefinition(FD); 581 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 582 EmitGlobalVarDefinition(VD); 583 } else { 584 assert(0 && "Invalid argument to EmitGlobalDefinition()"); 585 } 586 } 587 588 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 589 /// given global variable. If Ty is non-null and if the global doesn't exist, 590 /// then it will be greated with the specified type instead of whatever the 591 /// normal requested type would be. 592 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 593 const llvm::Type *Ty) { 594 assert(D->hasGlobalStorage() && "Not a global variable"); 595 596 QualType ASTTy = D->getType(); 597 if (Ty == 0) 598 Ty = getTypes().ConvertTypeForMem(ASTTy); 599 600 // Lookup the entry, lazily creating it if necessary. 601 const char *MangledName = getMangledName(D); 602 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 603 if (Entry) { 604 if (Entry->getType()->getElementType() == Ty && 605 Entry->getType()->getAddressSpace() == ASTTy.getAddressSpace()) 606 return Entry; 607 608 // Make sure the result is of the correct type. 609 const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace()); 610 return llvm::ConstantExpr::getBitCast(Entry, PTy); 611 } 612 613 llvm::GlobalVariable *GV = 614 new llvm::GlobalVariable(Ty, false, 615 llvm::GlobalValue::ExternalLinkage, 616 0, MangledName, &getModule(), 617 0, ASTTy.getAddressSpace()); 618 619 // Handle things which are present even on external declarations. 620 621 // FIXME: This code is overly simple and should be merged with 622 // other global handling. 623 624 GV->setConstant(D->getType().isConstant(Context)); 625 626 // FIXME: Merge with other attribute handling code. 627 628 if (D->getStorageClass() == VarDecl::PrivateExtern) 629 setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility); 630 631 if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>()) 632 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 633 634 return Entry = GV; 635 } 636 637 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) { 638 llvm::Constant *Init = 0; 639 QualType ASTTy = D->getType(); 640 641 if (D->getInit() == 0) { 642 // This is a tentative definition; tentative definitions are 643 // implicitly initialized with { 0 } 644 const llvm::Type *InitTy = getTypes().ConvertTypeForMem(ASTTy); 645 if (ASTTy->isIncompleteArrayType()) { 646 // An incomplete array is normally [ TYPE x 0 ], but we need 647 // to fix it to [ TYPE x 1 ]. 648 const llvm::ArrayType* ATy = cast<llvm::ArrayType>(InitTy); 649 InitTy = llvm::ArrayType::get(ATy->getElementType(), 1); 650 } 651 Init = llvm::Constant::getNullValue(InitTy); 652 } else { 653 Init = EmitConstantExpr(D->getInit()); 654 if (!Init) { 655 ErrorUnsupported(D, "static initializer"); 656 QualType T = D->getInit()->getType(); 657 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 658 } 659 } 660 661 const llvm::Type* InitType = Init->getType(); 662 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType); 663 664 // Strip off a bitcast if we got one back. 665 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) { 666 assert(CE->getOpcode() == llvm::Instruction::BitCast); 667 Entry = CE->getOperand(0); 668 } 669 670 // Entry is now either a Function or GlobalVariable. 671 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry); 672 673 // If we already have this global and it has an initializer, then 674 // we are in the rare situation where we emitted the defining 675 // declaration of the global and are now being asked to emit a 676 // definition which would be common. This occurs, for example, in 677 // the following situation because statics can be emitted out of 678 // order: 679 // 680 // static int x; 681 // static int *y = &x; 682 // static int x = 10; 683 // int **z = &y; 684 // 685 // Bail here so we don't blow away the definition. Note that if we 686 // can't distinguish here if we emitted a definition with a null 687 // initializer, but this case is safe. 688 if (GV && GV->hasInitializer() && !GV->getInitializer()->isNullValue()) { 689 assert(!D->getInit() && "Emitting multiple definitions of a decl!"); 690 return; 691 } 692 693 // We have a definition after a declaration with the wrong type. 694 // We must make a new GlobalVariable* and update everything that used OldGV 695 // (a declaration or tentative definition) with the new GlobalVariable* 696 // (which will be a definition). 697 // 698 // This happens if there is a prototype for a global (e.g. 699 // "extern int x[];") and then a definition of a different type (e.g. 700 // "int x[10];"). This also happens when an initializer has a different type 701 // from the type of the global (this happens with unions). 702 // 703 // FIXME: This also ends up happening if there's a definition followed by 704 // a tentative definition! (Although Sema rejects that construct 705 // at the moment.) 706 if (GV == 0 || 707 GV->getType()->getElementType() != InitType || 708 GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) { 709 710 // Remove the old entry from GlobalDeclMap so that we'll create a new one. 711 GlobalDeclMap.erase(getMangledName(D)); 712 713 // Make a new global with the correct type, this is now guaranteed to work. 714 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType)); 715 716 // Replace all uses of the old global with the new global 717 llvm::Constant *NewPtrForOldDecl = 718 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 719 Entry->replaceAllUsesWith(NewPtrForOldDecl); 720 721 // Erase the old global, since it is no longer used. 722 // FIXME: What if it was attribute used? Dangling pointer from LLVMUsed. 723 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 724 } 725 726 if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) { 727 SourceManager &SM = Context.getSourceManager(); 728 AddAnnotation(EmitAnnotateAttr(GV, AA, 729 SM.getInstantiationLineNumber(D->getLocation()))); 730 } 731 732 GV->setInitializer(Init); 733 GV->setConstant(D->getType().isConstant(Context)); 734 GV->setAlignment(getContext().getDeclAlignInBytes(D)); 735 736 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 737 setGlobalVisibility(GV, attr->getVisibility()); 738 // FIXME: else handle -fvisibility 739 740 // Set the llvm linkage type as appropriate. 741 if (D->getStorageClass() == VarDecl::Static) 742 GV->setLinkage(llvm::Function::InternalLinkage); 743 else if (D->getAttr<DLLImportAttr>()) 744 GV->setLinkage(llvm::Function::DLLImportLinkage); 745 else if (D->getAttr<DLLExportAttr>()) 746 GV->setLinkage(llvm::Function::DLLExportLinkage); 747 else if (D->getAttr<WeakAttr>() || D->getAttr<WeakImportAttr>()) 748 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 749 else { 750 // FIXME: This isn't right. This should handle common linkage and other 751 // stuff. 752 switch (D->getStorageClass()) { 753 case VarDecl::Static: assert(0 && "This case handled above"); 754 case VarDecl::Auto: 755 case VarDecl::Register: 756 assert(0 && "Can't have auto or register globals"); 757 case VarDecl::None: 758 if (!D->getInit()) 759 GV->setLinkage(llvm::GlobalVariable::CommonLinkage); 760 else 761 GV->setLinkage(llvm::GlobalVariable::ExternalLinkage); 762 break; 763 case VarDecl::Extern: 764 // FIXME: common 765 break; 766 767 case VarDecl::PrivateExtern: 768 GV->setVisibility(llvm::GlobalValue::HiddenVisibility); 769 // FIXME: common 770 break; 771 } 772 } 773 774 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 775 GV->setSection(SA->getName()); 776 777 if (D->getAttr<UsedAttr>()) 778 AddUsedGlobal(GV); 779 780 // Emit global variable debug information. 781 if (CGDebugInfo *DI = getDebugInfo()) { 782 DI->setLocation(D->getLocation()); 783 DI->EmitGlobalVariable(GV, D); 784 } 785 } 786 787 /// GetAddrOfFunction - Return the address of the given function. If Ty is 788 /// non-null, then this function will use the specified type if it has to 789 /// create it (this occurs when we see a definition of the function). 790 llvm::Function *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D, 791 const llvm::Type *Ty) { 792 // Lookup the entry, lazily creating it if necessary. 793 const char *MangledName = getMangledName(D); 794 llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName]; 795 if (Entry) 796 return cast<llvm::Function>(Entry); 797 798 // If there was no specific requested type, just convert it now. 799 if (!Ty) 800 Ty = getTypes().ConvertType(D->getType()); 801 802 // This function doesn't have a complete type (for example, the return 803 // type is an incomplete struct). Use a fake type instead, and make 804 // sure not to try to set attributes. 805 bool ShouldSetAttributes = true; 806 if (!isa<llvm::FunctionType>(Ty)) { 807 Ty = llvm::FunctionType::get(llvm::Type::VoidTy, 808 std::vector<const llvm::Type*>(), false); 809 ShouldSetAttributes = false; 810 } 811 llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty), 812 llvm::Function::ExternalLinkage, 813 MangledName, &getModule()); 814 if (ShouldSetAttributes) 815 SetFunctionAttributes(D, F); 816 Entry = F; 817 return F; 818 } 819 820 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) { 821 const llvm::FunctionType *Ty = 822 cast<llvm::FunctionType>(getTypes().ConvertType(D->getType())); 823 824 // As a special case, make sure that definitions of K&R function 825 // "type foo()" aren't declared as varargs (which forces the backend 826 // to do unnecessary work). 827 // FIXME: what about stret() functions, this doesn't handle them!? 828 if (Ty->isVarArg() && Ty->getNumParams() == 0) 829 Ty = llvm::FunctionType::get(Ty->getReturnType(), 830 std::vector<const llvm::Type*>(), false); 831 832 // Get or create the prototype for teh function. 833 llvm::Function *Fn = GetAddrOfFunction(D, Ty); 834 835 if (Fn->getType()->getElementType() != Ty) { 836 // If the types mismatch then we have to rewrite the definition. 837 assert(Fn->isDeclaration() && "Shouldn't replace non-declaration"); 838 839 // F is the Function* for the one with the wrong type, we must make a new 840 // Function* and update everything that used F (a declaration) with the new 841 // Function* (which will be a definition). 842 // 843 // This happens if there is a prototype for a function 844 // (e.g. "int f()") and then a definition of a different type 845 // (e.g. "int f(int x)"). Start by making a new function of the 846 // correct type, RAUW, then steal the name. 847 GlobalDeclMap.erase(getMangledName(D)); 848 llvm::Function *NewFn = GetAddrOfFunction(D, Ty); 849 NewFn->takeName(Fn); 850 851 // Replace uses of F with the Function we will endow with a body. 852 llvm::Constant *NewPtrForOldDecl = 853 llvm::ConstantExpr::getBitCast(NewFn, Fn->getType()); 854 Fn->replaceAllUsesWith(NewPtrForOldDecl); 855 856 // Ok, delete the old function now, which is dead. 857 // FIXME: If it was attribute(used) the pointer will dangle from the 858 // LLVMUsed array! 859 Fn->eraseFromParent(); 860 861 Fn = NewFn; 862 } 863 864 CodeGenFunction(*this).GenerateCode(D, Fn); 865 866 SetFunctionAttributesForDefinition(D, Fn); 867 868 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 869 AddGlobalCtor(Fn, CA->getPriority()); 870 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 871 AddGlobalDtor(Fn, DA->getPriority()); 872 } 873 874 llvm::Function * 875 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy, 876 const std::string &Name) { 877 llvm::Function *Fn = llvm::Function::Create(FTy, 878 llvm::Function::ExternalLinkage, 879 "", &TheModule); 880 RuntimeGlobals.push_back(std::make_pair(Fn, Name)); 881 return Fn; 882 } 883 884 llvm::GlobalVariable * 885 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty, 886 const std::string &Name) { 887 llvm::GlobalVariable *GV = 888 new llvm::GlobalVariable(Ty, /*Constant=*/false, 889 llvm::GlobalValue::ExternalLinkage, 890 0, "", &TheModule); 891 RuntimeGlobals.push_back(std::make_pair(GV, Name)); 892 return GV; 893 } 894 895 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 896 // Make sure that this type is translated. 897 Types.UpdateCompletedType(TD); 898 } 899 900 901 /// getBuiltinLibFunction 902 llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) { 903 if (BuiltinID > BuiltinFunctions.size()) 904 BuiltinFunctions.resize(BuiltinID); 905 906 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve 907 // a slot for it. 908 assert(BuiltinID && "Invalid Builtin ID"); 909 llvm::Value *&FunctionSlot = BuiltinFunctions[BuiltinID-1]; 910 if (FunctionSlot) 911 return FunctionSlot; 912 913 assert((Context.BuiltinInfo.isLibFunction(BuiltinID) || 914 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) && 915 "isn't a lib fn"); 916 917 // Get the name, skip over the __builtin_ prefix (if necessary). 918 const char *Name = Context.BuiltinInfo.GetName(BuiltinID); 919 if (Context.BuiltinInfo.isLibFunction(BuiltinID)) 920 Name += 10; 921 922 // Get the type for the builtin. 923 Builtin::Context::GetBuiltinTypeError Error; 924 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context, Error); 925 assert(Error == Builtin::Context::GE_None && "Can't get builtin type"); 926 927 const llvm::FunctionType *Ty = 928 cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 929 930 // FIXME: This has a serious problem with code like this: 931 // void abs() {} 932 // ... __builtin_abs(x); 933 // The two versions of abs will collide. The fix is for the builtin to win, 934 // and for the existing one to be turned into a constantexpr cast of the 935 // builtin. In the case where the existing one is a static function, it 936 // should just be renamed. 937 if (llvm::Function *Existing = getModule().getFunction(Name)) { 938 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage()) 939 return FunctionSlot = Existing; 940 assert(Existing == 0 && "FIXME: Name collision"); 941 } 942 943 llvm::GlobalValue *&ExistingFn = 944 GlobalDeclMap[getContext().Idents.get(Name).getName()]; 945 assert(!ExistingFn && "Asking for the same builtin multiple times?"); 946 947 // FIXME: param attributes for sext/zext etc. 948 return FunctionSlot = ExistingFn = 949 llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name, 950 &getModule()); 951 } 952 953 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 954 unsigned NumTys) { 955 return llvm::Intrinsic::getDeclaration(&getModule(), 956 (llvm::Intrinsic::ID)IID, Tys, NumTys); 957 } 958 959 llvm::Function *CodeGenModule::getMemCpyFn() { 960 if (MemCpyFn) return MemCpyFn; 961 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(); 962 return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1); 963 } 964 965 llvm::Function *CodeGenModule::getMemMoveFn() { 966 if (MemMoveFn) return MemMoveFn; 967 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(); 968 return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1); 969 } 970 971 llvm::Function *CodeGenModule::getMemSetFn() { 972 if (MemSetFn) return MemSetFn; 973 const llvm::Type *IntPtr = TheTargetData.getIntPtrType(); 974 return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1); 975 } 976 977 static void appendFieldAndPadding(CodeGenModule &CGM, 978 std::vector<llvm::Constant*>& Fields, 979 FieldDecl *FieldD, FieldDecl *NextFieldD, 980 llvm::Constant* Field, 981 RecordDecl* RD, const llvm::StructType *STy) { 982 // Append the field. 983 Fields.push_back(Field); 984 985 int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD); 986 987 int NextStructFieldNo; 988 if (!NextFieldD) { 989 NextStructFieldNo = STy->getNumElements(); 990 } else { 991 NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD); 992 } 993 994 // Append padding 995 for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) { 996 llvm::Constant *C = 997 llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1)); 998 999 Fields.push_back(C); 1000 } 1001 } 1002 1003 // We still need to work out the details of handling UTF-16. 1004 // See: <rdr://2996215> 1005 llvm::Constant *CodeGenModule:: 1006 GetAddrOfConstantCFString(const std::string &str) { 1007 llvm::StringMapEntry<llvm::Constant *> &Entry = 1008 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1009 1010 if (Entry.getValue()) 1011 return Entry.getValue(); 1012 1013 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); 1014 llvm::Constant *Zeros[] = { Zero, Zero }; 1015 1016 if (!CFConstantStringClassRef) { 1017 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 1018 Ty = llvm::ArrayType::get(Ty, 0); 1019 1020 // FIXME: This is fairly broken if 1021 // __CFConstantStringClassReference is already defined, in that it 1022 // will get renamed and the user will most likely see an opaque 1023 // error message. This is a general issue with relying on 1024 // particular names. 1025 llvm::GlobalVariable *GV = 1026 new llvm::GlobalVariable(Ty, false, 1027 llvm::GlobalVariable::ExternalLinkage, 0, 1028 "__CFConstantStringClassReference", 1029 &getModule()); 1030 1031 // Decay array -> ptr 1032 CFConstantStringClassRef = 1033 llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2); 1034 } 1035 1036 QualType CFTy = getContext().getCFConstantStringType(); 1037 RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl(); 1038 1039 const llvm::StructType *STy = 1040 cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 1041 1042 std::vector<llvm::Constant*> Fields; 1043 RecordDecl::field_iterator Field = CFRD->field_begin(); 1044 1045 // Class pointer. 1046 FieldDecl *CurField = *Field++; 1047 FieldDecl *NextField = *Field++; 1048 appendFieldAndPadding(*this, Fields, CurField, NextField, 1049 CFConstantStringClassRef, CFRD, STy); 1050 1051 // Flags. 1052 CurField = NextField; 1053 NextField = *Field++; 1054 const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy); 1055 appendFieldAndPadding(*this, Fields, CurField, NextField, 1056 llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy); 1057 1058 // String pointer. 1059 CurField = NextField; 1060 NextField = *Field++; 1061 llvm::Constant *C = llvm::ConstantArray::get(str); 1062 C = new llvm::GlobalVariable(C->getType(), true, 1063 llvm::GlobalValue::InternalLinkage, 1064 C, ".str", &getModule()); 1065 appendFieldAndPadding(*this, Fields, CurField, NextField, 1066 llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2), 1067 CFRD, STy); 1068 1069 // String length. 1070 CurField = NextField; 1071 NextField = 0; 1072 Ty = getTypes().ConvertType(getContext().LongTy); 1073 appendFieldAndPadding(*this, Fields, CurField, NextField, 1074 llvm::ConstantInt::get(Ty, str.length()), CFRD, STy); 1075 1076 // The struct. 1077 C = llvm::ConstantStruct::get(STy, Fields); 1078 llvm::GlobalVariable *GV = 1079 new llvm::GlobalVariable(C->getType(), true, 1080 llvm::GlobalVariable::InternalLinkage, 1081 C, "", &getModule()); 1082 1083 GV->setSection("__DATA,__cfstring"); 1084 Entry.setValue(GV); 1085 1086 return GV; 1087 } 1088 1089 /// GetStringForStringLiteral - Return the appropriate bytes for a 1090 /// string literal, properly padded to match the literal type. 1091 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) { 1092 const char *StrData = E->getStrData(); 1093 unsigned Len = E->getByteLength(); 1094 1095 const ConstantArrayType *CAT = 1096 getContext().getAsConstantArrayType(E->getType()); 1097 assert(CAT && "String isn't pointer or array!"); 1098 1099 // Resize the string to the right size. 1100 std::string Str(StrData, StrData+Len); 1101 uint64_t RealLen = CAT->getSize().getZExtValue(); 1102 1103 if (E->isWide()) 1104 RealLen *= getContext().Target.getWCharWidth()/8; 1105 1106 Str.resize(RealLen, '\0'); 1107 1108 return Str; 1109 } 1110 1111 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 1112 /// constant array for the given string literal. 1113 llvm::Constant * 1114 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) { 1115 // FIXME: This can be more efficient. 1116 return GetAddrOfConstantString(GetStringForStringLiteral(S)); 1117 } 1118 1119 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 1120 /// array for the given ObjCEncodeExpr node. 1121 llvm::Constant * 1122 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 1123 std::string Str; 1124 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1125 1126 return GetAddrOfConstantCString(Str); 1127 } 1128 1129 1130 /// GenerateWritableString -- Creates storage for a string literal. 1131 static llvm::Constant *GenerateStringLiteral(const std::string &str, 1132 bool constant, 1133 CodeGenModule &CGM, 1134 const char *GlobalName) { 1135 // Create Constant for this string literal. Don't add a '\0'. 1136 llvm::Constant *C = llvm::ConstantArray::get(str, false); 1137 1138 // Create a global variable for this string 1139 return new llvm::GlobalVariable(C->getType(), constant, 1140 llvm::GlobalValue::InternalLinkage, 1141 C, GlobalName ? GlobalName : ".str", 1142 &CGM.getModule()); 1143 } 1144 1145 /// GetAddrOfConstantString - Returns a pointer to a character array 1146 /// containing the literal. This contents are exactly that of the 1147 /// given string, i.e. it will not be null terminated automatically; 1148 /// see GetAddrOfConstantCString. Note that whether the result is 1149 /// actually a pointer to an LLVM constant depends on 1150 /// Feature.WriteableStrings. 1151 /// 1152 /// The result has pointer to array type. 1153 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str, 1154 const char *GlobalName) { 1155 // Don't share any string literals if writable-strings is turned on. 1156 if (Features.WritableStrings) 1157 return GenerateStringLiteral(str, false, *this, GlobalName); 1158 1159 llvm::StringMapEntry<llvm::Constant *> &Entry = 1160 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 1161 1162 if (Entry.getValue()) 1163 return Entry.getValue(); 1164 1165 // Create a global variable for this. 1166 llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName); 1167 Entry.setValue(C); 1168 return C; 1169 } 1170 1171 /// GetAddrOfConstantCString - Returns a pointer to a character 1172 /// array containing the literal and a terminating '\-' 1173 /// character. The result has pointer to array type. 1174 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str, 1175 const char *GlobalName){ 1176 return GetAddrOfConstantString(str + '\0', GlobalName); 1177 } 1178 1179 /// EmitObjCPropertyImplementations - Emit information for synthesized 1180 /// properties for an implementation. 1181 void CodeGenModule::EmitObjCPropertyImplementations(const 1182 ObjCImplementationDecl *D) { 1183 for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(), 1184 e = D->propimpl_end(); i != e; ++i) { 1185 ObjCPropertyImplDecl *PID = *i; 1186 1187 // Dynamic is just for type-checking. 1188 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 1189 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1190 1191 // Determine which methods need to be implemented, some may have 1192 // been overridden. Note that ::isSynthesized is not the method 1193 // we want, that just indicates if the decl came from a 1194 // property. What we want to know is if the method is defined in 1195 // this implementation. 1196 if (!D->getInstanceMethod(PD->getGetterName())) 1197 CodeGenFunction(*this).GenerateObjCGetter( 1198 const_cast<ObjCImplementationDecl *>(D), PID); 1199 if (!PD->isReadOnly() && 1200 !D->getInstanceMethod(PD->getSetterName())) 1201 CodeGenFunction(*this).GenerateObjCSetter( 1202 const_cast<ObjCImplementationDecl *>(D), PID); 1203 } 1204 } 1205 } 1206 1207 /// EmitTopLevelDecl - Emit code for a single top level declaration. 1208 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 1209 // If an error has occurred, stop code generation, but continue 1210 // parsing and semantic analysis (to ensure all warnings and errors 1211 // are emitted). 1212 if (Diags.hasErrorOccurred()) 1213 return; 1214 1215 switch (D->getKind()) { 1216 case Decl::Function: 1217 case Decl::Var: 1218 EmitGlobal(cast<ValueDecl>(D)); 1219 break; 1220 1221 case Decl::Namespace: 1222 ErrorUnsupported(D, "namespace"); 1223 break; 1224 1225 // Objective-C Decls 1226 1227 // Forward declarations, no (immediate) code generation. 1228 case Decl::ObjCClass: 1229 case Decl::ObjCForwardProtocol: 1230 break; 1231 1232 case Decl::ObjCProtocol: 1233 case Decl::ObjCCategory: 1234 case Decl::ObjCInterface: { 1235 ObjCContainerDecl *OCD = cast<ObjCContainerDecl>(D); 1236 for (ObjCContainerDecl::tuvar_iterator i = OCD->tuvar_begin(), 1237 e = OCD->tuvar_end(); i != e; ++i) { 1238 VarDecl *VD = *i; 1239 EmitGlobal(VD); 1240 } 1241 if (D->getKind() == Decl::ObjCProtocol) 1242 Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D)); 1243 break; 1244 } 1245 1246 case Decl::ObjCCategoryImpl: 1247 // Categories have properties but don't support synthesize so we 1248 // can ignore them here. 1249 1250 Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 1251 break; 1252 1253 case Decl::ObjCImplementation: { 1254 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D); 1255 EmitObjCPropertyImplementations(OMD); 1256 Runtime->GenerateClass(OMD); 1257 break; 1258 } 1259 case Decl::ObjCMethod: { 1260 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D); 1261 // If this is not a prototype, emit the body. 1262 if (OMD->getBody()) 1263 CodeGenFunction(*this).GenerateObjCMethod(OMD); 1264 break; 1265 } 1266 case Decl::ObjCCompatibleAlias: 1267 // compatibility-alias is a directive and has no code gen. 1268 break; 1269 1270 case Decl::LinkageSpec: { 1271 LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D); 1272 if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx) 1273 ErrorUnsupported(LSD, "linkage spec"); 1274 // FIXME: implement C++ linkage, C linkage works mostly by C 1275 // language reuse already. 1276 break; 1277 } 1278 1279 case Decl::FileScopeAsm: { 1280 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D); 1281 std::string AsmString(AD->getAsmString()->getStrData(), 1282 AD->getAsmString()->getByteLength()); 1283 1284 const std::string &S = getModule().getModuleInlineAsm(); 1285 if (S.empty()) 1286 getModule().setModuleInlineAsm(AsmString); 1287 else 1288 getModule().setModuleInlineAsm(S + '\n' + AsmString); 1289 break; 1290 } 1291 1292 default: 1293 // Make sure we handled everything we should, every other kind is 1294 // a non-top-level decl. FIXME: Would be nice to have an 1295 // isTopLevelDeclKind function. Need to recode Decl::Kind to do 1296 // that easily. 1297 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 1298 } 1299 } 1300