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