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 "CodeGenFunction.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/Basic/Diagnostic.h" 19 #include "clang/Basic/LangOptions.h" 20 #include "clang/Basic/TargetInfo.h" 21 #include "llvm/CallingConv.h" 22 #include "llvm/Constants.h" 23 #include "llvm/DerivedTypes.h" 24 #include "llvm/Module.h" 25 #include "llvm/Intrinsics.h" 26 #include <algorithm> 27 using namespace clang; 28 using namespace CodeGen; 29 30 31 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO, 32 llvm::Module &M, const llvm::TargetData &TD, 33 Diagnostic &diags) 34 : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags), 35 Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) { 36 //TODO: Make this selectable at runtime 37 Runtime = CreateObjCRuntime(M, 38 getTypes().ConvertType(getContext().IntTy), 39 getTypes().ConvertType(getContext().LongTy)); 40 } 41 42 CodeGenModule::~CodeGenModule() { 43 llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction(); 44 if (ObjCInitFunction) 45 AddGlobalCtor(ObjCInitFunction); 46 EmitGlobalCtors(); 47 delete Runtime; 48 } 49 50 /// WarnUnsupported - Print out a warning that codegen doesn't support the 51 /// specified stmt yet. 52 void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) { 53 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning, 54 "cannot codegen this %0 yet"); 55 SourceRange Range = S->getSourceRange(); 56 std::string Msg = Type; 57 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID, 58 &Msg, 1, &Range, 1); 59 } 60 61 /// WarnUnsupported - Print out a warning that codegen doesn't support the 62 /// specified decl yet. 63 void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) { 64 unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning, 65 "cannot codegen this %0 yet"); 66 std::string Msg = Type; 67 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID, 68 &Msg, 1); 69 } 70 71 /// AddGlobalCtor - Add a function to the list that will be called before 72 /// main() runs. 73 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) { 74 // TODO: Type coercion of void()* types. 75 GlobalCtors.push_back(Ctor); 76 } 77 78 /// EmitGlobalCtors - Generates the array of contsturctor functions to be 79 /// called on module load, if any have been registered with AddGlobalCtor. 80 void CodeGenModule::EmitGlobalCtors() { 81 if (GlobalCtors.empty()) return; 82 83 // Get the type of @llvm.global_ctors 84 std::vector<const llvm::Type*> CtorFields; 85 CtorFields.push_back(llvm::IntegerType::get(32)); 86 // Constructor function type 87 std::vector<const llvm::Type*> VoidArgs; 88 llvm::FunctionType* CtorFuncTy = 89 llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false); 90 91 // i32, function type pair 92 const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy); 93 llvm::StructType* CtorStructTy = 94 llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL); 95 // Array of fields 96 llvm::ArrayType* GlobalCtorsTy = 97 llvm::ArrayType::get(CtorStructTy, GlobalCtors.size()); 98 99 // Define the global variable 100 llvm::GlobalVariable *GlobalCtorsVal = 101 new llvm::GlobalVariable(GlobalCtorsTy, false, 102 llvm::GlobalValue::AppendingLinkage, 103 (llvm::Constant*)0, "llvm.global_ctors", 104 &TheModule); 105 106 // Populate the array 107 std::vector<llvm::Constant*> CtorValues; 108 llvm::Constant *MagicNumber = 109 llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false); 110 std::vector<llvm::Constant*> StructValues; 111 for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(), 112 E = GlobalCtors.end(); I != E; ++I) { 113 StructValues.clear(); 114 StructValues.push_back(MagicNumber); 115 StructValues.push_back(*I); 116 117 CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues)); 118 } 119 120 GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy, 121 CtorValues)); 122 } 123 124 125 126 /// ReplaceMapValuesWith - This is a really slow and bad function that 127 /// searches for any entries in GlobalDeclMap that point to OldVal, changing 128 /// them to point to NewVal. This is badbadbad, FIXME! 129 void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal, 130 llvm::Constant *NewVal) { 131 for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator 132 I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I) 133 if (I->second == OldVal) I->second = NewVal; 134 } 135 136 137 llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D, 138 bool isDefinition) { 139 // See if it is already in the map. If so, just return it. 140 llvm::Constant *&Entry = GlobalDeclMap[D]; 141 if (Entry) return Entry; 142 143 const llvm::Type *Ty = getTypes().ConvertType(D->getType()); 144 145 // Check to see if the function already exists. 146 llvm::Function *F = getModule().getFunction(D->getName()); 147 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty); 148 149 // If it doesn't already exist, just create and return an entry. 150 if (F == 0) { 151 // FIXME: param attributes for sext/zext etc. 152 F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, D->getName(), 153 &getModule()); 154 155 // Set the appropriate calling convention for the Function. 156 if (D->getAttr<FastCallAttr>()) 157 F->setCallingConv(llvm::CallingConv::Fast); 158 return Entry = F; 159 } 160 161 // If the pointer type matches, just return it. 162 llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty); 163 if (PFTy == F->getType()) return Entry = F; 164 165 // If this isn't a definition, just return it casted to the right type. 166 if (!isDefinition) 167 return Entry = llvm::ConstantExpr::getBitCast(F, PFTy); 168 169 // Otherwise, we have a definition after a prototype with the wrong type. 170 // F is the Function* for the one with the wrong type, we must make a new 171 // Function* and update everything that used F (a declaration) with the new 172 // Function* (which will be a definition). 173 // 174 // This happens if there is a prototype for a function (e.g. "int f()") and 175 // then a definition of a different type (e.g. "int f(int x)"). Start by 176 // making a new function of the correct type, RAUW, then steal the name. 177 llvm::Function *NewFn = llvm::Function::Create(FTy, 178 llvm::Function::ExternalLinkage, 179 "", &getModule()); 180 NewFn->takeName(F); 181 182 // Replace uses of F with the Function we will endow with a body. 183 llvm::Constant *NewPtrForOldDecl = 184 llvm::ConstantExpr::getBitCast(NewFn, F->getType()); 185 F->replaceAllUsesWith(NewPtrForOldDecl); 186 187 // FIXME: Update the globaldeclmap for the previous decl of this name. We 188 // really want a way to walk all of these, but we don't have it yet. This 189 // is incredibly slow! 190 ReplaceMapValuesWith(F, NewPtrForOldDecl); 191 192 // Ok, delete the old function now, which is dead. 193 assert(F->isDeclaration() && "Shouldn't replace non-declaration"); 194 F->eraseFromParent(); 195 196 // Return the new function which has the right type. 197 return Entry = NewFn; 198 } 199 200 static bool IsZeroElementArray(const llvm::Type *Ty) { 201 if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty)) 202 return ATy->getNumElements() == 0; 203 return false; 204 } 205 206 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 207 bool isDefinition) { 208 assert(D->hasGlobalStorage() && "Not a global variable"); 209 210 // See if it is already in the map. 211 llvm::Constant *&Entry = GlobalDeclMap[D]; 212 if (Entry) return Entry; 213 214 QualType ASTTy = D->getType(); 215 const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy); 216 217 // Check to see if the global already exists. 218 llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true); 219 220 // If it doesn't already exist, just create and return an entry. 221 if (GV == 0) { 222 return Entry = new llvm::GlobalVariable(Ty, false, 223 llvm::GlobalValue::ExternalLinkage, 224 0, D->getName(), &getModule(), 0, 225 ASTTy.getAddressSpace()); 226 } 227 228 // If the pointer type matches, just return it. 229 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 230 if (PTy == GV->getType()) return Entry = GV; 231 232 // If this isn't a definition, just return it casted to the right type. 233 if (!isDefinition) 234 return Entry = llvm::ConstantExpr::getBitCast(GV, PTy); 235 236 237 // Otherwise, we have a definition after a prototype with the wrong type. 238 // GV is the GlobalVariable* for the one with the wrong type, we must make a 239 /// new GlobalVariable* and update everything that used GV (a declaration) 240 // with the new GlobalVariable* (which will be a definition). 241 // 242 // This happens if there is a prototype for a global (e.g. "extern int x[];") 243 // and then a definition of a different type (e.g. "int x[10];"). Start by 244 // making a new global of the correct type, RAUW, then steal the name. 245 llvm::GlobalVariable *NewGV = 246 new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage, 247 0, D->getName(), &getModule(), 0, 248 ASTTy.getAddressSpace()); 249 NewGV->takeName(GV); 250 251 // Replace uses of GV with the globalvalue we will endow with a body. 252 llvm::Constant *NewPtrForOldDecl = 253 llvm::ConstantExpr::getBitCast(NewGV, GV->getType()); 254 GV->replaceAllUsesWith(NewPtrForOldDecl); 255 256 // FIXME: Update the globaldeclmap for the previous decl of this name. We 257 // really want a way to walk all of these, but we don't have it yet. This 258 // is incredibly slow! 259 ReplaceMapValuesWith(GV, NewPtrForOldDecl); 260 261 // Verify that GV was a declaration or something like x[] which turns into 262 // [0 x type]. 263 assert((GV->isDeclaration() || 264 IsZeroElementArray(GV->getType()->getElementType())) && 265 "Shouldn't replace non-declaration"); 266 267 // Ok, delete the old global now, which is dead. 268 GV->eraseFromParent(); 269 270 // Return the new global which has the right type. 271 return Entry = NewGV; 272 } 273 274 275 void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) { 276 // If this is not a prototype, emit the body. 277 if (OMD->getBody()) 278 CodeGenFunction(*this).GenerateObjCMethod(OMD); 279 } 280 281 void CodeGenModule::EmitFunction(const FunctionDecl *FD) { 282 // If this is not a prototype, emit the body. 283 if (FD->getBody()) 284 CodeGenFunction(*this).GenerateCode(FD); 285 } 286 287 llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) { 288 return EmitConstantExpr(Expr); 289 } 290 291 void CodeGenModule::EmitGlobalVar(const VarDecl *D) { 292 // If this is just a forward declaration of the variable, don't emit it now, 293 // allow it to be emitted lazily on its first use. 294 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0) 295 return; 296 297 // Get the global, forcing it to be a direct reference. 298 llvm::GlobalVariable *GV = 299 cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true)); 300 301 // Convert the initializer, or use zero if appropriate. 302 llvm::Constant *Init = 0; 303 if (D->getInit() == 0) { 304 Init = llvm::Constant::getNullValue(GV->getType()->getElementType()); 305 } else if (D->getType()->isIntegerType()) { 306 llvm::APSInt Value(static_cast<uint32_t>( 307 getContext().getTypeSize(D->getInit()->getType()))); 308 if (D->getInit()->isIntegerConstantExpr(Value, Context)) 309 Init = llvm::ConstantInt::get(Value); 310 } 311 312 if (!Init) 313 Init = EmitGlobalInit(D->getInit()); 314 315 assert(GV->getType()->getElementType() == Init->getType() && 316 "Initializer codegen type mismatch!"); 317 GV->setInitializer(Init); 318 319 if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) 320 GV->setVisibility(attr->getVisibility()); 321 // FIXME: else handle -fvisibility 322 323 // Set the llvm linkage type as appropriate. 324 if (D->getAttr<DLLImportAttr>()) 325 GV->setLinkage(llvm::Function::DLLImportLinkage); 326 else if (D->getAttr<DLLExportAttr>()) 327 GV->setLinkage(llvm::Function::DLLExportLinkage); 328 else if (D->getAttr<WeakAttr>()) { 329 GV->setLinkage(llvm::GlobalVariable::WeakLinkage); 330 331 } else { 332 // FIXME: This isn't right. This should handle common linkage and other 333 // stuff. 334 switch (D->getStorageClass()) { 335 case VarDecl::Auto: 336 case VarDecl::Register: 337 assert(0 && "Can't have auto or register globals"); 338 case VarDecl::None: 339 if (!D->getInit()) 340 GV->setLinkage(llvm::GlobalVariable::WeakLinkage); 341 break; 342 case VarDecl::Extern: 343 case VarDecl::PrivateExtern: 344 // todo: common 345 break; 346 case VarDecl::Static: 347 GV->setLinkage(llvm::GlobalVariable::InternalLinkage); 348 break; 349 } 350 } 351 } 352 353 /// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified 354 /// declarator chain. 355 void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) { 356 for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator())) 357 if (D->isFileVarDecl()) 358 EmitGlobalVar(D); 359 } 360 361 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 362 // Make sure that this type is translated. 363 Types.UpdateCompletedType(TD); 364 } 365 366 367 /// getBuiltinLibFunction 368 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) { 369 if (BuiltinID > BuiltinFunctions.size()) 370 BuiltinFunctions.resize(BuiltinID); 371 372 // Cache looked up functions. Since builtin id #0 is invalid we don't reserve 373 // a slot for it. 374 assert(BuiltinID && "Invalid Builtin ID"); 375 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1]; 376 if (FunctionSlot) 377 return FunctionSlot; 378 379 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn"); 380 381 // Get the name, skip over the __builtin_ prefix. 382 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10; 383 384 // Get the type for the builtin. 385 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context); 386 const llvm::FunctionType *Ty = 387 cast<llvm::FunctionType>(getTypes().ConvertType(Type)); 388 389 // FIXME: This has a serious problem with code like this: 390 // void abs() {} 391 // ... __builtin_abs(x); 392 // The two versions of abs will collide. The fix is for the builtin to win, 393 // and for the existing one to be turned into a constantexpr cast of the 394 // builtin. In the case where the existing one is a static function, it 395 // should just be renamed. 396 if (llvm::Function *Existing = getModule().getFunction(Name)) { 397 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage()) 398 return FunctionSlot = Existing; 399 assert(Existing == 0 && "FIXME: Name collision"); 400 } 401 402 // FIXME: param attributes for sext/zext etc. 403 return FunctionSlot = llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, 404 Name, &getModule()); 405 } 406 407 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys, 408 unsigned NumTys) { 409 return llvm::Intrinsic::getDeclaration(&getModule(), 410 (llvm::Intrinsic::ID)IID, Tys, NumTys); 411 } 412 413 llvm::Function *CodeGenModule::getMemCpyFn() { 414 if (MemCpyFn) return MemCpyFn; 415 llvm::Intrinsic::ID IID; 416 switch (Context.Target.getPointerWidth(0)) { 417 default: assert(0 && "Unknown ptr width"); 418 case 32: IID = llvm::Intrinsic::memcpy_i32; break; 419 case 64: IID = llvm::Intrinsic::memcpy_i64; break; 420 } 421 return MemCpyFn = getIntrinsic(IID); 422 } 423 424 llvm::Function *CodeGenModule::getMemSetFn() { 425 if (MemSetFn) return MemSetFn; 426 llvm::Intrinsic::ID IID; 427 switch (Context.Target.getPointerWidth(0)) { 428 default: assert(0 && "Unknown ptr width"); 429 case 32: IID = llvm::Intrinsic::memset_i32; break; 430 case 64: IID = llvm::Intrinsic::memset_i64; break; 431 } 432 return MemSetFn = getIntrinsic(IID); 433 } 434 435 llvm::Constant *CodeGenModule:: 436 GetAddrOfConstantCFString(const std::string &str) { 437 llvm::StringMapEntry<llvm::Constant *> &Entry = 438 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 439 440 if (Entry.getValue()) 441 return Entry.getValue(); 442 443 std::vector<llvm::Constant*> Fields; 444 445 if (!CFConstantStringClassRef) { 446 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 447 Ty = llvm::ArrayType::get(Ty, 0); 448 449 CFConstantStringClassRef = 450 new llvm::GlobalVariable(Ty, false, 451 llvm::GlobalVariable::ExternalLinkage, 0, 452 "__CFConstantStringClassReference", 453 &getModule()); 454 } 455 456 // Class pointer. 457 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); 458 llvm::Constant *Zeros[] = { Zero, Zero }; 459 llvm::Constant *C = 460 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2); 461 Fields.push_back(C); 462 463 // Flags. 464 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 465 Fields.push_back(llvm::ConstantInt::get(Ty, 1992)); 466 467 // String pointer. 468 C = llvm::ConstantArray::get(str); 469 C = new llvm::GlobalVariable(C->getType(), true, 470 llvm::GlobalValue::InternalLinkage, 471 C, ".str", &getModule()); 472 473 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2); 474 Fields.push_back(C); 475 476 // String length. 477 Ty = getTypes().ConvertType(getContext().LongTy); 478 Fields.push_back(llvm::ConstantInt::get(Ty, str.length())); 479 480 // The struct. 481 Ty = getTypes().ConvertType(getContext().getCFConstantStringType()); 482 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields); 483 llvm::GlobalVariable *GV = 484 new llvm::GlobalVariable(C->getType(), true, 485 llvm::GlobalVariable::InternalLinkage, 486 C, "", &getModule()); 487 GV->setSection("__DATA,__cfstring"); 488 Entry.setValue(GV); 489 return GV; 490 } 491 492 /// GenerateWritableString -- Creates storage for a string literal. 493 static llvm::Constant *GenerateStringLiteral(const std::string &str, 494 bool constant, 495 CodeGenModule &CGM) { 496 // Create Constant for this string literal 497 llvm::Constant *C=llvm::ConstantArray::get(str); 498 499 // Create a global variable for this string 500 C = new llvm::GlobalVariable(C->getType(), constant, 501 llvm::GlobalValue::InternalLinkage, 502 C, ".str", &CGM.getModule()); 503 return C; 504 } 505 506 /// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character 507 /// array containing the literal. The result is pointer to array type. 508 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) { 509 // Don't share any string literals if writable-strings is turned on. 510 if (Features.WritableStrings) 511 return GenerateStringLiteral(str, false, *this); 512 513 llvm::StringMapEntry<llvm::Constant *> &Entry = 514 ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); 515 516 if (Entry.getValue()) 517 return Entry.getValue(); 518 519 // Create a global variable for this. 520 llvm::Constant *C = GenerateStringLiteral(str, true, *this); 521 Entry.setValue(C); 522 return C; 523 } 524