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